import React, { useState, useEffect } 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 { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, Calendar as CalendarIcon, StickyNote } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { logBulkUpdate, logStatusChange, logStageChange } from '@/lib/violationTimelineLogger';

export function BulkViolationUpdateDialog({ open, onOpenChange, selectedIds = [], onSuccess }) {
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [updates, setUpdates] = useState({
    status: null, stage: null, priority: null, assigned_to: null,
    violation_date: '', due_date: '', notes: ''
  });

  const handleSubmit = async () => {
    setLoading(true);
    try {
      const updatePayload = {};
      const timestamp = new Date().toISOString();

      if (updates.status && updates.status !== 'no_change') {
        // If status is "fined", mark as "closed" instead
        updatePayload.status = updates.status.toLowerCase() === 'fined' ? 'closed' : updates.status;
      }
      if (updates.priority && updates.priority !== 'no_change') updatePayload.priority = updates.priority;
      if (updates.assigned_to && updates.assigned_to !== 'no_change') updatePayload.assigned_to = updates.assigned_to;
      if (updates.violation_date) updatePayload.violation_date = updates.violation_date;
      if (updates.due_date) updatePayload.due_date = updates.due_date;
      if (updates.notes && updates.notes.trim() !== '') updatePayload.notes = updates.notes;
      if (updates.stage && updates.stage !== 'no_change') {
        updatePayload.stage = updates.stage;
      }

      if (Object.keys(updatePayload).length === 0) { onOpenChange(false); return; }

      // Fetch current state of all selected violations for change tracking
      const { data: currentViolations } = await supabase.from('violations').select('id, status, stage, notice_level').in('id', selectedIds);

      const { error } = await supabase.from('violations').update(updatePayload).in('id', selectedIds);
      if (error) throw error;

      // Auto-log timeline for each affected violation
      const logPromises = selectedIds.map(async (id) => {
        const current = currentViolations?.find(v => v.id === id);
        await logBulkUpdate(id, updatePayload);
        if (updatePayload.status && current && current.status !== updatePayload.status) {
          await logStatusChange(id, current.status, updatePayload.status);
        }
        if (updatePayload.stage && current && (current.stage || current.notice_level) !== updatePayload.stage) {
          await logStageChange(id, current.stage || current.notice_level, updatePayload.stage);
        }
      });
      await Promise.allSettled(logPromises);

      onSuccess(selectedIds.length);
      onOpenChange(false);
      setUpdates({ status: null, stage: null, priority: null, assigned_to: null, violation_date: '', due_date: '', notes: '' });
    } catch (error) {
      console.error('Bulk update error:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px] max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Bulk Update Violations</DialogTitle>
          <DialogDescription>
            Updating <span className="font-semibold text-primary">{selectedIds.length}</span> selected violation(s).
          </DialogDescription>
        </DialogHeader>
        
        <div className="grid gap-4 py-4">
          <div className="space-y-4 border rounded-md p-4 bg-muted/30">
             <h4 className="font-medium text-sm flex items-center gap-2">
                <CalendarIcon className="w-4 h-4" /> Update Dates
             </h4>
             <div className="grid grid-cols-2 gap-4">
                 <div>
                    <Label className="text-xs mb-1.5 block">New Violation Date</Label>
                    <Input type="date" value={updates.violation_date} onChange={(e) => setUpdates(prev => ({ ...prev, violation_date: e.target.value }))} />
                 </div>
                 <div>
                    <Label className="text-xs mb-1.5 block">New Due Date</Label>
                    <Input type="date" value={updates.due_date} onChange={(e) => setUpdates(prev => ({ ...prev, due_date: e.target.value }))} />
                 </div>
             </div>
          </div>

          <div className="space-y-4">
            <h4 className="font-medium text-sm border-t pt-2">Other Properties</h4>
            <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right text-xs">Status</Label>
                <Select value={updates.status || 'no_change'} onValueChange={(val) => setUpdates(prev => ({ ...prev, status: val }))}>
                  <SelectTrigger className="col-span-3 h-8 text-xs"><SelectValue placeholder="No Change" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="no_change">No Change</SelectItem>
                    <SelectItem value="open">Open</SelectItem>
                    <SelectItem value="resolved">Resolved</SelectItem>
                    <SelectItem value="recommended_for_fining">Recommended for Fining</SelectItem>
                    <SelectItem value="fined">Fined</SelectItem>
                    <SelectItem value="closed">Closed</SelectItem>
                  </SelectContent>
                </Select>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right text-xs">Stage</Label>
                <Select value={updates.stage || 'no_change'} onValueChange={(val) => setUpdates(prev => ({ ...prev, stage: val }))}>
                  <SelectTrigger className="col-span-3 h-8 text-xs"><SelectValue placeholder="No Change" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="no_change">No Change</SelectItem>
                    <SelectItem value="First Notice">First Notice</SelectItem>
                    <SelectItem value="Second Notice">Second Notice</SelectItem>
                    <SelectItem value="Third & Final Notice">Third & Final Notice</SelectItem>
                  </SelectContent>
                </Select>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right text-xs">Priority</Label>
                <Select value={updates.priority || 'no_change'} onValueChange={(val) => setUpdates(prev => ({ ...prev, priority: val }))}>
                  <SelectTrigger className="col-span-3 h-8 text-xs"><SelectValue placeholder="No Change" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="no_change">No Change</SelectItem>
                    <SelectItem value="low">Low</SelectItem>
                    <SelectItem value="medium">Medium</SelectItem>
                    <SelectItem value="high">High</SelectItem>
                  </SelectContent>
                </Select>
            </div>
            
            <div className="space-y-2 pt-2">
                 <Label className="text-xs flex items-center gap-2">
                    <StickyNote className="w-3 h-3" /> Optional Notes (Overwrites existing)
                 </Label>
                 <Textarea value={updates.notes} onChange={(e) => setUpdates(prev => ({ ...prev, notes: e.target.value }))} placeholder="Add a note to all selected violations..." className="h-20 text-xs" />
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleSubmit} disabled={loading}>
            {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
            Confirm Update
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
