"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Trash2, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { deleteLead } from "./actions";

interface DeleteLeadDialogProps {
  leadId: string;
  leadName?: string;
  trigger?: React.ReactNode;
  redirectToLeads?: boolean;
}

export function DeleteLeadDialog({
  leadId,
  leadName,
  trigger,
  redirectToLeads = false,
}: DeleteLeadDialogProps) {
  const [open, setOpen] = useState(false);
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  function handleDelete() {
    startTransition(async () => {
      const res = await deleteLead(leadId);
      if (res.ok) {
        toast.success(`Lead ${leadName ? `"${leadName}" ` : ""}deleted successfully`);
        setOpen(false);
        if (redirectToLeads) {
          router.push("/leads");
        } else {
          router.refresh();
        }
      } else {
        toast.error(res.error ?? "Failed to delete lead");
      }
    });
  }

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>
        {trigger ?? (
          <Button variant="outline" size="sm" className="text-destructive hover:bg-destructive/10 hover:text-destructive">
            <Trash2 className="mr-1.5 size-4" />
            Delete
          </Button>
        )}
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Are you sure you want to delete this lead?</AlertDialogTitle>
          <AlertDialogDescription>
            This will permanently delete {leadName ? <strong className="text-foreground">{leadName}</strong> : "this lead"} and remove all associated notes, follow-ups, and assignments. This action cannot be undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={pending}>Cancel</AlertDialogCancel>
          <Button
            variant="destructive"
            onClick={handleDelete}
            disabled={pending}
          >
            {pending ? (
              <>
                <Loader2 className="mr-2 size-4 animate-spin" />
                Deleting…
              </>
            ) : (
              "Delete Lead"
            )}
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
