"use client";

import { useTransition } from "react";
import { Loader2, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { deleteCustomerAction } from "@/lib/appwrite/customer-actions";

export function DeleteCustomerDialog({
  open,
  onOpenChange,
  id,
  name,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  id: string | null;
  name: string;
}) {
  const [isPending, startTransition] = useTransition();

  const handleDelete = () => {
    if (!id) return;
    startTransition(async () => {
      const fd = new FormData();
      fd.set("id", id);
      const result = await deleteCustomerAction(fd);
      if (result.ok) {
        toast.success("Müşteri silindi.");
        onOpenChange(false);
      } else {
        toast.error(result.error ?? "Silme başarısız.");
      }
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Müşteriyi sil</DialogTitle>
          <DialogDescription>
            <strong>{name}</strong> kalıcı olarak silinecek. Bu işlem geri alınamaz.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
            Vazgeç
          </Button>
          <Button variant="destructive" onClick={handleDelete} disabled={isPending}>
            {isPending ? (
              <>
                <Loader2 className="size-4 animate-spin" />
                Siliniyor...
              </>
            ) : (
              <>
                <Trash2 className="size-4" />
                Sil
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
