import { useState, useEffect } from "react";
import {
  AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle,
  AlertDialogDescription, AlertDialogFooter, AlertDialogCancel,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { AlertTriangle, Loader2, ArrowRight } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/components/ui/use-toast";
import type { Tables } from "@/integrations/supabase/types";

type ChartOfAccount = Tables<"chart_of_accounts">;

interface DeleteChartOfAccountDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  account: ChartOfAccount | null;
  allAccounts?: ChartOfAccount[];
  onSuccess: () => void;
}

export default function DeleteChartOfAccountDialog({
  open,
  onOpenChange,
  account,
  allAccounts = [],
  onSuccess,
}: DeleteChartOfAccountDialogProps) {
  const { toast } = useToast();
  const [checking, setChecking] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // Check for journal entries referencing this account
  const [journalCount, setJournalCount] = useState(0);

  useEffect(() => {
    if (open && account) {
      checkDependencies();
    } else {
      setJournalCount(0);
    }
  }, [open, account]);

  const checkDependencies = async () => {
    if (!account) return;
    setChecking(true);
    try {
      const { count, error } = await supabase
        .from("journal_entries")
        .select("*", { count: "exact", head: true })
        .eq("chart_of_account_id", account.id);

      if (error) throw error;
      setJournalCount(count ?? 0);
    } catch (err) {
      console.error("Error checking dependencies:", err);
      toast({ variant: "destructive", title: "Error", description: "Failed to check account dependencies." });
    } finally {
      setChecking(false);
    }
  };

  const handleConfirm = async () => {
    if (!account) return;
    setIsDeleting(true);

    try {
      if (journalCount > 0) {
        throw new Error(
          `Cannot delete this account because it is referenced by ${journalCount} journal entries. Remove those references first.`
        );
      }

      const { error: delErr } = await supabase
        .from("chart_of_accounts")
        .delete()
        .eq("id", account.id);

      if (delErr) {
        if (delErr.code === "23503") {
          throw new Error(
            "Cannot delete this account because it is still referenced by other financial records."
          );
        }
        throw delErr;
      }

      toast({ title: "Account Deleted", description: "The account was successfully deleted." });
      onSuccess();
      onOpenChange(false);
    } catch (err: any) {
      console.error("Delete failed:", err);
      toast({ variant: "destructive", title: "Deletion Failed", description: err.message });
    } finally {
      setIsDeleting(false);
    }
  };

  if (!account) return null;

  const canSubmit = !isDeleting && journalCount === 0;

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent className="max-w-xl">
        <AlertDialogHeader>
          <AlertDialogTitle className="flex items-center gap-2 text-destructive">
            <AlertTriangle className="w-5 h-5" />
            Delete Account: {account.account_name}
          </AlertDialogTitle>
          <AlertDialogDescription asChild>
            <div className="space-y-4 pt-2">
              <p className="text-foreground">
                You are about to delete{" "}
                <span className="font-bold">
                  {account.account_number} - {account.account_name}
                </span>
                . This action is permanent.
              </p>

              {checking ? (
                <div className="flex items-center gap-2 p-4 bg-muted text-muted-foreground rounded-md">
                  <Loader2 className="w-4 h-4 animate-spin" /> Checking account dependencies...
                </div>
              ) : (
                <>
                  {journalCount > 0 && (
                    <div className="p-4 bg-destructive/10 border border-destructive/20 rounded-md space-y-2">
                      <div className="flex items-start gap-2 text-destructive">
                        <AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
                        <div>
                          <strong className="block text-sm">Cannot Delete</strong>
                          <p className="text-xs mt-1">
                            This account is referenced by{" "}
                            <strong>{journalCount} journal entries</strong>. Remove those references
                            before deleting.
                          </p>
                        </div>
                      </div>
                    </div>
                  )}

                  {journalCount === 0 && (
                    <p className="text-muted-foreground text-sm">
                      No dependencies found. This action cannot be undone.
                    </p>
                  )}
                </>
              )}
            </div>
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter className="mt-6 border-t pt-4">
          <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
          <Button
            variant="destructive"
            onClick={handleConfirm}
            disabled={!canSubmit || checking}
          >
            {isDeleting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
            Confirm Delete
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
