"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { useConfirm } from "@/components/shared/use-confirm";

export function UserActions({
  userId,
  isVerified,
  isBanned,
  isSuspended,
  userType,
}: {
  userId: number;
  isVerified: boolean;
  isBanned: boolean;
  isSuspended: boolean;
  userType: string;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState<string | null>(null);
  const [showBanModal, setShowBanModal] = useState(false);
  const [showRoleModal, setShowRoleModal] = useState(false);
  const [banReason, setBanReason] = useState("");
  const [selectedRole, setSelectedRole] = useState(userType);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  async function handleAction(
    action: string,
    url: string,
    body?: Record<string, unknown>
  ) {
    if (!(await askConfirm({ title: action.charAt(0).toUpperCase() + action.slice(1), message: `Are you sure you want to ${action} this user?` }))) return;
    setLoading(action);
    try {
      const res = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body || {}),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data.error || `Failed to ${action}`);
      } else {
        router.refresh();
      }
    } catch {
      alert(`Failed to ${action}`);
    } finally {
      setLoading(null);
    }
  }

  return (
    <>
      {confirmDialog}
      <div className="flex items-center gap-2">
        {!isVerified && (
          <button
            disabled={loading !== null}
            onClick={() =>
              handleAction("verify", `/api/admin/users/${userId}/verify`)
            }
            className="bg-green-600 hover:bg-green-700 text-white px-3 py-1.5 rounded-lg transition-colors text-sm disabled:opacity-50"
          >
            {loading === "verify" ? "..." : "Verify"}
          </button>
        )}

        {!isBanned ? (
          <button
            disabled={loading !== null}
            onClick={() => setShowBanModal(true)}
            className="bg-red-600 hover:bg-red-700 text-white px-3 py-1.5 rounded-lg transition-colors text-sm disabled:opacity-50"
          >
            Ban
          </button>
        ) : (
          <button
            disabled={loading !== null}
            onClick={() =>
              handleAction("unban", `/api/admin/users/${userId}/ban`, {
                unban: true,
              })
            }
            className="bg-yellow-600 hover:bg-yellow-700 text-white px-3 py-1.5 rounded-lg transition-colors text-sm disabled:opacity-50"
          >
            {loading === "unban" ? "..." : "Unban"}
          </button>
        )}

        <button
          disabled={loading !== null}
          onClick={async () => {
            if (!(await askConfirm({ title: "Impersonate user", message: "Impersonate this user? You will be redirected to their dashboard." }))) return;
            setLoading("impersonate");
            try {
              const res = await fetch("/api/admin/impersonate", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ user_id: userId }),
              });
              if (res.ok) {
                const data = await res.json();
                window.location.href = data.redirect || "/dashboard";
              } else {
                const data = await res.json().catch(() => ({}));
                alert(data.error || "Failed to impersonate user");
              }
            } catch {
              alert("Failed to impersonate user");
            } finally {
              setLoading(null);
            }
          }}
          className="bg-purple-600 hover:bg-purple-700 text-white px-3 py-1.5 rounded-lg transition-colors text-sm disabled:opacity-50"
        >
          {loading === "impersonate" ? "..." : "Impersonate"}
        </button>

        <button
          disabled={loading !== null}
          onClick={() => setShowRoleModal(true)}
          className="bg-surface-light hover:bg-surface text-text px-3 py-1.5 rounded-lg transition-colors text-sm border border-surface-light disabled:opacity-50"
        >
          Change Role
        </button>

        {/* A.2: prior to Round 11 the Delete button POSTed { delete: true }
            to /ban, but the server required a typed confirm token, so every
            click 400'd silently. Route through the GDPR anonymise endpoint
            (data-erasure, not hard delete) which is the safer default. */}
        <button
          disabled={loading !== null}
          onClick={() =>
            handleAction(
              "anonymise",
              `/api/admin/users/${userId}/delete-data`,
              { confirm: `GDPR_DELETE_${userId}` },
            )
          }
          className="bg-red-900 hover:bg-red-800 text-white px-3 py-1.5 rounded-lg transition-colors text-sm disabled:opacity-50"
        >
          Delete (GDPR)
        </button>
      </div>

      {/* Ban Modal */}
      {showBanModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
          <div className="bg-surface rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-semibold mb-4">Ban User</h3>
            <label className="block text-text-muted text-sm mb-1">
              Reason
            </label>
            <textarea
              value={banReason}
              onChange={(e) => setBanReason(e.target.value)}
              className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary mb-4"
              rows={3}
              placeholder="Enter ban reason..."
            />
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setShowBanModal(false)}
                className="bg-surface-light hover:bg-surface text-text-muted px-4 py-2 rounded-lg transition-colors text-sm"
              >
                Cancel
              </button>
              <button
                disabled={loading !== null}
                onClick={async () => {
                  setShowBanModal(false);
                  await handleAction(
                    "ban",
                    `/api/admin/users/${userId}/ban`,
                    { reason: banReason }
                  );
                  setBanReason("");
                }}
                className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                Confirm Ban
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Role Modal */}
      {showRoleModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
          <div className="bg-surface rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-semibold mb-4">Change Role</h3>
            <label className="block text-text-muted text-sm mb-1">Role</label>
            <select
              value={selectedRole}
              onChange={(e) => setSelectedRole(e.target.value)}
              className="w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary mb-4"
            >
              <option value="user">User</option>
              <option value="escort">Escort</option>
              <option value="admin">Admin</option>
              <option value="developer">Developer</option>
              <option value="strip_club">Strip Club</option>
              <option value="streamer">Streamer</option>
            </select>
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setShowRoleModal(false)}
                className="bg-surface-light hover:bg-surface text-text-muted px-4 py-2 rounded-lg transition-colors text-sm"
              >
                Cancel
              </button>
              <button
                disabled={loading !== null}
                onClick={async () => {
                  setShowRoleModal(false);
                  await handleAction(
                    "change role",
                    `/api/admin/users/${userId}/role`,
                    { role: selectedRole }
                  );
                }}
                className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                Save Role
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
