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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } 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 BulkCollectionStatusDialog({ 
  open, 
  onOpenChange, 
  selectedCollectionIds = new Set(), 
  collections = [], 
  onSuccess 
}) {
  const [newStatus, setNewStatus] = useState('');
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

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

  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"
  ];

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

    try {
      const { error } = await supabase
        .from('collections')
        .update({ status: newStatus, updated_at: new Date().toISOString() })
        .in('id', Array.from(selectedCollectionIds));

      if (error) throw error;

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

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

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Bulk Update Status</DialogTitle>
          <DialogDescription>
            Update the status for <span className="font-semibold">{selectedCollections.length}</span> selected collections.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="bg-amber-50 border border-amber-200 rounded-md p-3 flex gap-3 items-start">
             <AlertTriangle className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
             <div className="text-sm text-amber-800">
                This action will overwrite the status for all selected items. This cannot be undone automatically.
             </div>
          </div>

          <div className="space-y-2">
            <Label>New Status</Label>
            <Select value={newStatus} onValueChange={setNewStatus}>
              <SelectTrigger><SelectValue placeholder="Select new status..." /></SelectTrigger>
              <SelectContent>
                {statusOptions.map(status => (
                  <SelectItem key={status} value={status}>{status}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label className="text-xs text-muted-foreground">Selected Items</Label>
            <ScrollArea className="h-[150px] w-full border rounded-md p-2 bg-muted/50">
              {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>

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