import React, { 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 '@/hooks/use-toast';

export default function DeleteChartOfAccountDialogFull({ 
  open, 
  onOpenChange, 
  account, 
  allAccounts = [], 
  onSuccess 
}) {
  const { toast } = useToast();
  
  const [checking, setChecking] = useState(false);
  const [journalCount, setJournalCount] = useState(0);
  
  const [hasSubAccounts, setHasSubAccounts] = useState(false);
  const [deleteMode, setDeleteMode] = useState('cancel');
  const [newParentId, setNewParentId] = useState('none');
  
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    if (open && account) {
      checkDependencies();
    } else {
      setJournalCount(0);
      setHasSubAccounts(false);
      setDeleteMode('cancel');
      setNewParentId('none');
    }
  }, [open, account]);

  const checkDependencies = async () => {
    setChecking(true);
    try {
      const subs = allAccounts.filter(a => a.parent_account_id === account.id);
      setHasSubAccounts(subs.length > 0);
      
      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: ${journalCount} journal entries reference this account. Remove them first.`);
      }

      if (hasSubAccounts) {
        if (deleteMode === 'delete-all') {
          const childIds = allAccounts.filter(a => a.parent_account_id === account.id).map(a => a.id);
          if (childIds.length > 0) {
            const { error: childErr } = await supabase.from('chart_of_accounts').delete().in('id', childIds);
            if (childErr) throw childErr;
          }
        } else if (deleteMode === 'move') {
          const target = newParentId === 'none' ? null : newParentId;
          const { error: moveErr } = await supabase
            .from('chart_of_accounts')
            .update({ parent_account_id: target })
            .eq('parent_account_id', account.id);
          if (moveErr) throw moveErr;
        } else {
          setIsDeleting(false);
          return;
        }
      }

      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: still referenced by other financial records.");
        }
        throw delErr;
      }

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

  if (!account) return null;

  const canSubmit = !isDeleting && 
    (!hasSubAccounts || deleteMode !== 'cancel') && 
    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>
                  )}

                  {hasSubAccounts && journalCount === 0 && (
                    <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-md text-sm">
                      <strong className="block mb-2">Warning: This account has nested sub-accounts.</strong>
                      <p className="mb-3 text-xs text-muted-foreground">Choose how to handle the child accounts:</p>
                      
                      <div className="space-y-3 bg-background p-3 rounded border">
                        <div className="flex items-start space-x-2">
                          <input 
                            type="radio" 
                            id="del-all" 
                            name="del-mode" 
                            className="mt-1"
                            checked={deleteMode === 'delete-all'} 
                            onChange={() => setDeleteMode('delete-all')} 
                          />
                          <label htmlFor="del-all" className="cursor-pointer">
                            <strong className="block">Delete All</strong> 
                            <span className="text-xs text-muted-foreground">Remove this account AND all its sub-accounts permanently.</span>
                          </label>
                        </div>
                        
                        <div className="flex items-start space-x-2">
                          <input 
                            type="radio" 
                            id="del-move" 
                            name="del-mode"
                            className="mt-1"
                            checked={deleteMode === 'move'} 
                            onChange={() => setDeleteMode('move')} 
                          />
                          <div className="flex-1">
                            <label htmlFor="del-move" className="cursor-pointer">
                              <strong className="block">Move Sub-accounts</strong>
                              <span className="text-xs text-muted-foreground">Reassign sub-accounts to a new parent.</span>
                            </label>
                            {deleteMode === 'move' && (
                              <div className="mt-2">
                                <Select value={newParentId} onValueChange={setNewParentId}>
                                  <SelectTrigger className="h-9 w-full">
                                    <SelectValue placeholder="Select New Parent (or None)" />
                                  </SelectTrigger>
                                  <SelectContent className="max-h-60">
                                    <SelectItem value="none">-- Make Top Level (No Parent) --</SelectItem>
                                    {allAccounts
                                      .filter(a => a.id !== account.id && a.parent_account_id !== account.id)
                                      .map(a => (
                                        <SelectItem key={a.id} value={a.id}>
                                          {a.account_name} {a.account_number ? `(${a.account_number})` : ''}
                                        </SelectItem>
                                      ))
                                    }
                                  </SelectContent>
                                </Select>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {journalCount === 0 && !hasSubAccounts && (
                    <p className="text-muted-foreground text-sm">
                      No dependencies found. This action is permanent and 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>
  );
}
