import { ApiError } from "../../api/client";
import type { UserAdmin } from "../../api/types";
import { ConfirmDialog } from "../../components/ui/ConfirmDialog";
import { useToast } from "../../components/ui/toast-context";
import { useDeleteUser } from "./hooks";

interface DeleteUserDialogProps {
  /** The user pending deletion, or null when closed. */
  user: UserAdmin | null;
  onClose: () => void;
}

/**
 * Permanent user deletion behind the shared ConfirmDialog (a consequential,
 * irreversible action). The caller never opens this for the signed-in admin —
 * the page hides the Delete action on the self row and the server independently
 * rejects a self-delete — so this dialog only ever targets another user.
 */
export function DeleteUserDialog({ user, onClose }: DeleteUserDialogProps) {
  const toast = useToast();
  const del = useDeleteUser();

  function handleConfirm() {
    if (!user) return;
    del.mutate(user.id, {
      onSuccess: () => {
        toast.success("User deleted", `${user.username} can no longer sign in.`);
        onClose();
      },
      onError: (err) => {
        toast.error(
          "Could not delete user",
          err instanceof ApiError
            ? err.message
            : "The server did not respond. The user was not deleted.",
        );
      },
    });
  }

  return (
    <ConfirmDialog
      open={user != null}
      title="Delete user"
      danger
      busy={del.isPending}
      confirmLabel="Delete user"
      cancelLabel="Keep user"
      body={
        <span>
          Permanently delete{" "}
          <span className="mono">{user?.username}</span> and revoke their access
          to GuruConnect. This cannot be undone. To temporarily block sign-in
          without losing the account, disable it instead.
        </span>
      }
      onConfirm={handleConfirm}
      onCancel={onClose}
    />
  );
}
