import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, SelectGroup, SelectLabel } from '@/components/ui/select';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Loader2, AlertTriangle, CheckCircle2 } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export default function BulkCollectionFinancialEditDialog({ 
  open, 
  onOpenChange, 
  selectedCollectionIds = new Set(), 
  collections = [], 
  onSuccess 
}) {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const [selectedFields, setSelectedFields] = useState({
    status: false,
    deadline: false,
    amount_due: false
  });

  const [values, setValues] = useState({
    status: '',
    deadline: '',
    amount_due: ''
  });

  const selectedCollections = collections.filter(c => selectedCollectionIds.has(c.id));

  const handleFieldSelect = (field) => {
    setSelectedFields(prev => ({ ...prev, [field]: !prev[field] }));
  };

  const handleValueChange = (field, value) => {
    setValues(prev => ({ ...prev, [field]: value }));
  };

  const validate = () => {
    if (!selectedFields.status && !selectedFields.deadline && !selectedFields.amount_due) {
      toast({ variant: "destructive", title: "Validation Error", description: "Please select at least one field to update." });
      return false;
    }
    if (selectedFields.status && !values.status) {
      toast({ variant: "destructive", title: "Validation Error", description: "Please select a status." });
      return false;
    }
    if (selectedFields.deadline && !values.deadline) {
      toast({ variant: "destructive", title: "Validation Error", description: "Please select a deadline date." });
      return false;
    }
    if (selectedFields.amount_due) {
      if (values.amount_due === '' || isNaN(values.amount_due) || Number(values.amount_due) < 0) {
        toast({ variant: "destructive", title: "Validation Error", description: "Please enter a valid positive amount." });
        return false;
      }
    }
    return true;
  };

  const handleBulkUpdate = async () => {
    if (!validate()) return;
    setLoading(true);

    try {
      const updates = { updated_at: new Date().toISOString() };

      if (selectedFields.status) {
        updates.status = values.status;
      }

      const { error } = await supabase
        .from('collections')
        .update(updates)
        .in('id', Array.from(selectedCollectionIds));

      if (error) throw error;

      toast({ title: "Bulk Update Successful", description: `Updated ${selectedCollections.length} collections successfully.` });

      if (onSuccess) onSuccess();
      onOpenChange(false);
      setValues({ status: '', deadline: '', amount_due: '' });
      setSelectedFields({ status: false, deadline: false, amount_due: false });

    } catch (error) {
      console.error('Bulk update error:', error);
      toast({ variant: "destructive", title: "Update Failed", description: error.message });
    } finally {
      setLoading(false);
    }
  };

  const statusOptions = [
    "Draft", "Open", "Initial Notice Sent", "Official Notice Sent", "Final Notice Sent",
    "Notice of Late Assessment", "Notice of Intent to Lien", "With Attorney", "Lien Filed",
    "Foreclosure Initiated", "Foreclosed", "Payment Plan", "Bankruptcy Hold", "Resolved", "Written Off"
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Bulk Edit Collections</DialogTitle>
          <DialogDescription>
            Update multiple fields for <span className="font-semibold text-primary">{selectedCollections.length}</span> selected collections.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-4">
          <div className="space-y-4 border rounded-md p-4 bg-muted/30">
             <div className="flex items-start gap-3">
                <div className="pt-3">
                   <input type="checkbox" id="check_status" checked={selectedFields.status} onChange={() => handleFieldSelect('status')} className="h-4 w-4 rounded border-input" />
                </div>
                <div className="flex-1 space-y-2">
                   <Label htmlFor="check_status" className="cursor-pointer">Update Status</Label>
                   <Select value={values.status} onValueChange={(val) => handleValueChange('status', val)} disabled={!selectedFields.status}>
                    <SelectTrigger><SelectValue placeholder="Select Status..." /></SelectTrigger>
                    <SelectContent>
                      {statusOptions.map(status => (
                        <SelectItem key={status} value={status}>{status}</SelectItem>
                      ))}
                    </SelectContent>
                   </Select>
                </div>
             </div>

             <div className="flex items-start gap-3">
                <div className="pt-3">
                   <input type="checkbox" id="check_deadline" checked={selectedFields.deadline} onChange={() => handleFieldSelect('deadline')} className="h-4 w-4 rounded border-input" />
                </div>
                <div className="flex-1 space-y-2">
                   <Label htmlFor="check_deadline" className="cursor-pointer">Update Deadline</Label>
                   <Input type="date" value={values.deadline} onChange={(e) => handleValueChange('deadline', e.target.value)} disabled={!selectedFields.deadline} />
                </div>
             </div>

             <div className="flex items-start gap-3">
                <div className="pt-3">
                   <input type="checkbox" id="check_amount" checked={selectedFields.amount_due} onChange={() => handleFieldSelect('amount_due')} className="h-4 w-4 rounded border-input" />
                </div>
                <div className="flex-1 space-y-2">
                   <Label htmlFor="check_amount" className="cursor-pointer">Update Total Amount Due</Label>
                   <Input type="number" min="0" step="0.01" value={values.amount_due} onChange={(e) => handleValueChange('amount_due', e.target.value)} disabled={!selectedFields.amount_due} placeholder="0.00" />
                   <p className="text-[10px] text-muted-foreground">Note: This overrides the calculated total from individual fees.</p>
                </div>
             </div>
          </div>

          <div className="space-y-2">
            <Label className="text-xs text-muted-foreground">Selected Items Preview</Label>
            <ScrollArea className="h-[120px] w-full border rounded-md p-2">
              {selectedCollections.length === 0 ? (
                <div className="text-xs text-muted-foreground p-2">No items selected</div>
              ) : (
                <ul className="space-y-1">
                  {selectedCollections.map(c => (
                    <li key={c.id} className="text-xs flex items-center gap-2 py-1 border-b last:border-0">
                      <CheckCircle2 className="w-3 h-3 text-emerald-500" />
                      <span className="font-medium truncate max-w-[200px]">{c.address || c.id}</span>
                    </li>
                  ))}
                </ul>
              )}
            </ScrollArea>
          </div>

           <div className="bg-amber-50 border border-amber-200 rounded-md p-3 flex gap-3 items-start">
             <AlertTriangle className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
             <div className="text-xs text-amber-800">
                Are you sure? This action will overwrite data for all selected records and cannot be undone easily.
             </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>Cancel</Button>
          <Button onClick={handleBulkUpdate} disabled={loading || selectedCollections.length === 0 || (!selectedFields.status && !selectedFields.deadline && !selectedFields.amount_due)}>
            {loading ? (<><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Updating...</>) : 'Apply Changes'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
