import React, { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { AlertCircle, Loader2 } from 'lucide-react';

export default function DeleteWithReassignDialog({ open, onOpenChange, itemToDelete, itemType, entityName, availableReplacements, associationId, onSuccess }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [usageCount, setUsageCount] = useState(0);
  const [replacementName, setReplacementName] = useState('');
  const [checkingUsage, setCheckingUsage] = useState(false);

  useEffect(() => {
    if (open && itemToDelete && associationId) {
      checkUsage();
      setReplacementName('');
    }
  }, [open, itemToDelete, associationId]);

  const checkUsage = async () => {
    setCheckingUsage(true);
    try {
      let field = '';
      if (itemType === 'type') field = 'account_type';
      else if (itemType === 'category') field = 'account_type';
      else if (itemType === 'subcategory') field = 'account_type';

      const { count, error } = await supabase
        .from('chart_of_accounts')
        .select('id', { count: 'exact', head: true })
        .eq('association_id', associationId)
        .eq(field, itemToDelete.name);

      if (error) throw error;
      setUsageCount(count || 0);
    } catch (err) {
      console.error('Error checking usage:', err);
    } finally {
      setCheckingUsage(false);
    }
  };

  const handleDelete = async () => {
    if (usageCount > 0 && !replacementName) {
      toast({ variant: 'destructive', title: 'Action Required', description: 'Please select a replacement to reassign existing accounts.' });
      return;
    }

    setLoading(true);
    try {
      let field = '';
      if (itemType === 'type') field = 'account_type';
      else if (itemType === 'category') field = 'account_type';
      else if (itemType === 'subcategory') field = 'account_type';

      if (usageCount > 0) {
        const { error: updateError } = await supabase
          .from('chart_of_accounts')
          .update({ [field]: replacementName })
          .eq('association_id', associationId)
          .eq(field, itemToDelete.name);
        
        if (updateError) throw updateError;
      }

      toast({ title: 'Deleted Successfully', description: `Deleted ${entityName} and reassigned accounts if needed.` });
      onSuccess();
      onOpenChange(false);
    } catch (err) {
      console.error('Error deleting:', err);
      toast({ variant: 'destructive', title: 'Error', description: err.message });
    } finally {
      setLoading(false);
    }
  };

  const replacements = (availableReplacements || []).filter(r => r.name !== itemToDelete?.name);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[450px]">
        <DialogHeader>
          <DialogTitle className="text-destructive flex items-center gap-2">
            <AlertCircle className="w-5 h-5" /> Delete {entityName}
          </DialogTitle>
          <DialogDescription>
            Are you sure you want to delete the {entityName} "{itemToDelete?.name}"?
          </DialogDescription>
        </DialogHeader>

        <div className="py-4">
          {checkingUsage ? (
            <div className="flex items-center text-muted-foreground text-sm"><Loader2 className="w-4 h-4 animate-spin mr-2" /> Checking usage...</div>
          ) : usageCount > 0 ? (
            <div className="space-y-4">
              <div className="bg-yellow-50 text-yellow-800 p-3 rounded-md text-sm border border-yellow-200">
                This {entityName} is currently used by <strong>{usageCount}</strong> account(s). You must select a replacement to reassign these accounts before deleting.
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Reassign to:</label>
                <Select value={replacementName} onValueChange={setReplacementName}>
                  <SelectTrigger>
                    <SelectValue placeholder={`Select a replacement ${entityName}`} />
                  </SelectTrigger>
                  <SelectContent>
                    {replacements.map(r => (
                      <SelectItem key={r.name} value={r.name}>{r.name}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          ) : (
            <div className="text-muted-foreground text-sm">
              This {entityName} is not currently in use by any accounts. It is safe to delete.
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>Cancel</Button>
          <Button variant="destructive" onClick={handleDelete} disabled={loading || (usageCount > 0 && !replacementName)}>
            {loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
            Confirm Delete
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
