"use client";

import Button from "@/components/ui/button/Button";
import Input from "@/components/form/input/InputField";
import { useAuth } from "@/hooks/auth";
import { canConfirmAccountDeletion } from "./deleteAccountLogic";
import { AlertTriangle, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import React from "react";
import toast from "react-hot-toast";

type DeleteAccountCardProps = {
  userId: string;
  isOpen: boolean;
  onOpen: () => void;
  onClose: () => void;
};

export default function DeleteAccountCard({
  userId,
  isOpen,
  onOpen,
  onClose,
}: DeleteAccountCardProps) {
  const router = useRouter();
  const { logout } = useAuth();
  const [confirmation, setConfirmation] = React.useState("");
  const [deleting, setDeleting] = React.useState(false);

  const handleCancel = () => {
    if (deleting) return;
    setConfirmation("");
    onClose();
  };

  const handleDelete = async () => {
    if (!canConfirmAccountDeletion(confirmation) || deleting) return;

    setDeleting(true);
    try {
      const response = await fetch("/api/profile/delete", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId }),
      });
      const data = await response.json().catch(() => ({}));

      if (!response.ok || data?.ok === false) {
        throw new Error(data?.message || data?.error || "Failed to delete account");
      }

      toast.success(data?.message || "Account deleted successfully");
      await logout();
      router.replace("/signin?reason=account-deleted");
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Failed to delete account");
      setDeleting(false);
    }
  };

  if (!isOpen) {
    return (
      <section className="rounded-2xl border border-error-200 bg-error-50/40 p-5 dark:border-error-500/30 dark:bg-error-500/5 lg:p-6">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h4 className="mt-1 text-lg font-semibold text-gray-800 dark:text-white/90">
              Delete Account
            </h4>
            <p className="mt-2 max-w-2xl text-sm leading-6 text-gray-600 dark:text-gray-300">
              Deactivate your account and sign out of this application.
            </p>
          </div>
          <Button
            type="button"
            size="sm"
            variant="outline"
            className="border-error-300 text-error-600 hover:bg-error-100 dark:border-error-500/40 dark:text-error-400 dark:hover:bg-error-500/10"
            onClick={onOpen}
          >
            <Trash2 className="h-4 w-4" />
            Delete Account
          </Button>
        </div>
      </section>
    );
  }

  return (
    <section className="rounded-2xl border border-error-200 bg-error-50/40 p-5 dark:border-error-500/30 dark:bg-error-500/5 lg:p-6">
      <div className="flex items-start gap-3">
        <div className="mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-error-100 text-error-600 dark:bg-error-500/10 dark:text-error-400">
          <AlertTriangle className="h-5 w-5" />
        </div>
        <div>
          <h4 className="mt-1 text-lg font-semibold text-gray-800 dark:text-white/90">
            Permanently delete your account?
          </h4>
          <p className="mt-2 max-w-2xl text-sm leading-6 text-gray-600 dark:text-gray-300">
            This will deactivate your account and sign you out. This action cannot be undone from
            the application.
          </p>
        </div>
      </div>

      <div className="mt-5">
        <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
          Type <span className="font-semibold text-error-600 dark:text-error-400">DELETE</span> to
          confirm
        </label>
        <Input
          value={confirmation}
          onChange={(event) => setConfirmation(event.target.value)}
          placeholder="DELETE"
          disabled={deleting}
        />
      </div>

      <div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
        <Button type="button" variant="outline" onClick={handleCancel} disabled={deleting}>
          Cancel
        </Button>
        <Button
          type="button"
          className="bg-error-600 hover:bg-error-700"
          onClick={handleDelete}
          disabled={!canConfirmAccountDeletion(confirmation) || deleting}
        >
          {deleting ? "Deleting..." : "Permanently Delete"}
        </Button>
      </div>
    </section>
  );
}
