import React, { useState, useRef, useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { AlertTriangle, Calendar, MapPin, ExternalLink, ArrowRight, Pencil, History, Info, Upload, User, FileText, Camera, ImagePlus, Loader2, MessageSquare, Mail, Trash2, GitMerge } from "lucide-react";
import { cn } from '@/lib/utils';
import { useAuth } from '@/contexts/AuthContext';
import { useViolationTimeline } from '@/hooks/useViolationTimeline';
import { useToast } from '@/components/ui/use-toast';
import { supabase } from '@/integrations/supabase/client';
import ViolationTimelineManager from '@/components/ViolationTimelineManager';
import ViolationTimelineEntryDialog from '@/components/ViolationTimelineEntryDialog';
import ViolationTimelineImportDialog from '@/components/ViolationTimelineImportDialog';
import ViolationTimelineExportButton from '@/components/ViolationTimelineExportButton';
import ViolationMergeDialog from '@/components/ViolationMergeDialog';
import { formatPhotoTimestamp, getPhotoDate } from '@/lib/exifUtils';
import { Badge } from '@/components/ui/badge';
import { formatDateTimeShortEST, formatShortDateEST } from '@/lib/timezoneUtils';
import { logPhotoChange } from '@/lib/violationTimelineLogger';

export default function ViolationDetailsDialog({ open, onOpenChange, violation, onEdit, onUpdate, onStatusChange, onRegenerateNotice, onEmailNotice }) {
  const { userRole } = useAuth();
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState('details');
  const [isEntryDialogOpen, setIsEntryDialogOpen] = useState(false);
  const [isImportDialogOpen, setIsImportDialogOpen] = useState(false);
  const [isMergeDialogOpen, setIsMergeDialogOpen] = useState(false);
  const [editingEntry, setEditingEntry] = useState(null);
  const [isUpdatingStatus, setIsUpdatingStatus] = useState(false);
  const [isUploadingPhotos, setIsUploadingPhotos] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  const [isDeletingPhoto, setIsDeletingPhoto] = useState(null);
  const fileInputRef = useRef(null);

  // Responses state
  const [responses, setResponses] = useState([]);
  const [loadingResponses, setLoadingResponses] = useState(false);

  const canEdit = ['admin', 'manager', 'employee'].includes(userRole?.role);
  const { addEntry, updateEntry, deleteEntry, loading: timelineLoading } = useViolationTimeline(violation?.id, onUpdate);

  // Fetch responses when the tab is opened or violation changes
  useEffect(() => {
    if (!violation?.id || !open) return;
    fetchResponses();
  }, [violation?.id, open]);

  const fetchResponses = async () => {
    if (!violation?.id) return;
    setLoadingResponses(true);
    const { data, error } = await supabase
      .from("violation_responses")
      .select("*")
      .eq("violation_id", violation.id)
      .order("created_at", { ascending: false });
    if (!error) setResponses(data || []);
    setLoadingResponses(false);
  };

  const handleDeletePhoto = async (photoUrl, idx) => {
    if (!canEdit || !violation?.id) return;
    setIsDeletingPhoto(idx);
    try {
      const currentPhotos = Array.isArray(violation.photo_urls) ? [...violation.photo_urls] : violation.photo_url ? [{ url: violation.photo_url }] : [];
      const updatedPhotos = currentPhotos.filter((p) => {
        const url = typeof p === 'string' ? p : p?.url;
        return url !== photoUrl;
      });
      const { error } = await supabase.from('violations').update({
        photo_urls: updatedPhotos.length > 0 ? updatedPhotos : [],
        photo_url: updatedPhotos.length > 0 ? (typeof updatedPhotos[0] === 'string' ? updatedPhotos[0] : updatedPhotos[0]?.url) : null,
      }).eq('id', violation.id);
      if (error) throw error;
      toast({ title: 'Photo Deleted', description: 'The photo has been removed.' });
      await logPhotoChange(violation.id, 'removed', 1);
      if (onUpdate) onUpdate();
    } catch (err) {
      toast({ title: 'Delete Failed', description: err.message, variant: 'destructive' });
    } finally {
      setIsDeletingPhoto(null);
    }
  };

  if (!violation) return null;

  const formatDate = (dateString) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleDateString();
  };

  const handleStatusUpdate = async (newStatus) => {
    if (!onStatusChange) return;
    setIsUpdatingStatus(true);
    try {
      await onStatusChange(violation.id, newStatus);
      toast({ title: 'Status Updated', description: `Violation marked as ${newStatus}.` });
      if (onUpdate) onUpdate();
    } catch (err) {
      toast({ title: 'Update Failed', description: err.message, variant: 'destructive' });
    } finally {
      setIsUpdatingStatus(false);
    }
  };

  const handleSaveTimelineEntry = async (data) => {
    let success = false;
    if (editingEntry) { success = await updateEntry(editingEntry.id, data); }
    else { success = await addEntry(data); }
    if (success) { setIsEntryDialogOpen(false); setEditingEntry(null); }
  };

  const handleDrag = (e) => { e.preventDefault(); e.stopPropagation(); setDragActive(e.type === "dragenter" || e.type === "dragover"); };

  const handleDrop = async (e) => {
    e.preventDefault(); e.stopPropagation(); setDragActive(false);
    if (e.dataTransfer.files?.length > 0) await processPhotoUploads(Array.from(e.dataTransfer.files));
  };

  const handleFileSelect = async (e) => {
    if (e.target.files?.length > 0) await processPhotoUploads(Array.from(e.target.files));
  };

  const processPhotoUploads = async (files) => {
    const validFiles = files.filter(f => f.type.startsWith('image/'));
    if (validFiles.length === 0) { toast({ variant: 'destructive', title: 'Invalid Files' }); return; }
    setIsUploadingPhotos(true);
    try {
      const newUrls = [];
      for (const file of validFiles) {
        const captureTimestamp = await getPhotoDate(file);
        const fileName = `${uuidv4()}.${file.name.split('.').pop()}`;
        const { data: uploadData, error: uploadError } = await supabase.storage.from('violation-photos').upload(fileName, file);
        if (uploadError) throw uploadError;
        const { data: urlData } = supabase.storage.from('violation-photos').getPublicUrl(uploadData.path);
        newUrls.push({ url: urlData.publicUrl, timestamp: captureTimestamp || null });
      }
      let currentPhotos = Array.isArray(violation.photo_urls) ? [...violation.photo_urls] : violation.photo_url ? [{ url: violation.photo_url }] : [];
      const updatedPhotos = [...currentPhotos, ...newUrls];
      const { error } = await supabase.from('violations').update({ photo_urls: updatedPhotos, photo_url: updatedPhotos[0]?.url || null }).eq('id', violation.id);
      if (error) throw error;
      toast({ title: 'Upload Successful', description: `Added ${validFiles.length} photo(s).` });
      await logPhotoChange(violation.id, 'added', validFiles.length);
      if (onUpdate) onUpdate();
    } catch (err) {
      toast({ variant: 'destructive', title: 'Upload Failed', description: err.message });
    } finally {
      setIsUploadingPhotos(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const statusColors = {
    open: 'bg-red-100 text-red-800', resolved: 'bg-green-100 text-green-800',
  };

  const stageColors = {
    'First Notice': 'bg-blue-100 text-blue-700',
    'Second Notice': 'bg-orange-100 text-orange-700',
    'Third & Final Notice': 'bg-red-100 text-red-700',
  };

  const timelineEntries = Array.isArray(violation.timeline_entries) ? violation.timeline_entries : [];
  
  const normalizePhoto = (p) => typeof p === 'string' ? { url: p, timestamp: null } : p;
  const splitSemicolonUrls = (s) => s.split(/;\s*/).map(u => u.trim()).filter(Boolean);
  
  let displayPhotos = [];
  if (violation.photo_urls && Array.isArray(violation.photo_urls)) {
    displayPhotos = violation.photo_urls.flatMap(p => {
      const norm = normalizePhoto(p);
      return norm.url.includes(';') ? splitSemicolonUrls(norm.url).map(u => ({ url: u, timestamp: norm.timestamp || null })) : [norm];
    });
  } else if (violation.photo_url) {
    displayPhotos = splitSemicolonUrls(violation.photo_url).map(u => ({ url: u, timestamp: null }));
  }

  const getOwnerName = () => {
    if (violation.owners) return `${violation.owners.first_name || ''} ${violation.owners.last_name || ''}`.trim();
    return 'Unknown';
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] max-h-[90vh] flex flex-col bg-card p-0 gap-0 overflow-hidden">
        <DialogHeader className="p-6 pb-2 shrink-0">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-destructive/10 rounded-full"><AlertTriangle className="w-6 h-6 text-destructive" /></div>
            <div>
                <DialogTitle className="text-xl font-bold">Violation Details</DialogTitle>
                <DialogDescription>Review full details and history.</DialogDescription>
            </div>
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto px-6 py-2">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full h-full flex flex-col">
                <TabsList className="grid w-full grid-cols-3 bg-muted shrink-0">
                    <TabsTrigger value="details" className="gap-2"><Info className="w-4 h-4" /> Details</TabsTrigger>
                    <TabsTrigger value="responses" className="gap-2">
                      <MessageSquare className="w-4 h-4" /> Responses
                      {responses.length > 0 && <Badge variant="secondary" className="ml-1 h-4 px-1.5 text-[10px]">{responses.length}</Badge>}
                    </TabsTrigger>
                    <TabsTrigger value="timeline" className="gap-2"><History className="w-4 h-4" /> Timeline</TabsTrigger>
                </TabsList>

                <TabsContent value="details" className="py-4 space-y-6">
                    <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between p-4 bg-muted/50 rounded-lg border gap-4">
                        <div className="space-y-1">
                            <p className="text-xs uppercase tracking-wide font-semibold text-muted-foreground">Status</p>
                            {canEdit && onStatusChange ? (
                                <Select value={violation.status || 'open'} onValueChange={handleStatusUpdate} disabled={isUpdatingStatus}>
                                    <SelectTrigger className={`h-8 border-0 shadow-sm font-medium ${statusColors[violation.status?.toLowerCase()] || 'bg-muted'}`}><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="open">Open</SelectItem>
                                        <SelectItem value="resolved">Resolved</SelectItem>
                                    </SelectContent>
                                </Select>
                            ) : (
                                <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium capitalize ${statusColors[violation.status?.toLowerCase()] || 'bg-muted'}`}>{violation.status || 'Open'}</span>
                            )}
                        </div>
                        <div className="space-y-1">
                            <p className="text-xs uppercase tracking-wide font-semibold text-muted-foreground">Stage</p>
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium ${stageColors[violation.stage] || 'bg-muted'}`}>
                                {violation.stage || 'First Notice'}
                            </span>
                            {canEdit && onStatusChange && violation.status !== 'resolved' && violation.stage !== 'Third & Final Notice' && (
                                <Button size="sm" variant="outline" className="ml-2 h-7 text-[11px] gap-1" onClick={() => handleStatusUpdate('escalated')} disabled={isUpdatingStatus}>
                                    <ArrowRight className="w-3 h-3" /> Escalate
                                </Button>
                            )}
                        </div>
                        <div className="text-left sm:text-right space-y-1">
                            <p className="text-xs uppercase tracking-wide font-semibold text-muted-foreground">Violation Type</p>
                            <p className="text-base font-bold">{violation.violation_type || violation.title || 'General'}</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="space-y-4">
                            <div className="flex items-start space-x-3">
                                <MapPin className="w-5 h-5 text-muted-foreground mt-0.5" />
                                <div>
                                    <p className="text-sm font-medium text-muted-foreground">Property</p>
                                    <p className="font-medium">{violation.owners?.property_address || violation.address || 'N/A'}</p>
                                    {violation.associations?.name && <p className="text-sm text-muted-foreground mt-0.5">{violation.associations.name}</p>}
                                </div>
                            </div>
                            <div className="flex items-start space-x-3">
                                <User className="w-5 h-5 text-muted-foreground mt-0.5" />
                                <div><p className="text-sm font-medium text-muted-foreground">Owner</p><p>{getOwnerName()}</p></div>
                            </div>
                        </div>
                        <div className="space-y-4">
                            <div className="flex items-start space-x-3">
                                <Calendar className="w-5 h-5 text-muted-foreground mt-0.5" />
                                <div><p className="text-sm font-medium text-muted-foreground">Date Reported</p><p>{formatDate(violation.violation_date || violation.created_at)}</p></div>
                            </div>
                            {violation.due_date && (
                                <div className="flex items-start space-x-3">
                                    <Calendar className="w-5 h-5 text-destructive mt-0.5" />
                                    <div><p className="text-sm font-medium text-muted-foreground">Resolution Due</p><p className="font-medium">{formatDate(violation.due_date)}</p></div>
                                </div>
                            )}
                            {violation.certified_mail && (
                                <div className="flex items-start space-x-3">
                                    <FileText className="w-5 h-5 text-muted-foreground mt-0.5" />
                                    <div><p className="text-sm font-medium text-muted-foreground">Certified Mail #</p><p className="font-mono text-sm">{violation.certified_mail}</p></div>
                                </div>
                            )}
                        </div>
                    </div>

                    {(violation.description || violation.notes) && (
                        <div className="space-y-2">
                            <div className="flex items-center gap-2"><FileText className="w-4 h-4 text-muted-foreground"/><p className="text-sm font-medium">Description & Notes</p></div>
                            <div className="p-4 bg-muted/50 rounded-md border text-sm leading-relaxed whitespace-pre-wrap">
                                {violation.description && <div className="mb-2">{violation.description}</div>}
                                {violation.notes && <div>{violation.notes}</div>}
                            </div>
                        </div>
                    )}

                    <div className="space-y-3 pb-4">
                        <p className="text-sm font-medium">Evidence Photos</p>
                        {displayPhotos.length > 0 && (
                            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 mb-4">
                                {displayPhotos.map((photo, idx) => (
                                    <div key={idx} className="space-y-1">
                                        <div className="relative rounded-lg overflow-hidden border bg-muted/50 group aspect-video">
                                            <img src={photo.url} alt={`Evidence ${idx + 1}`} className="w-full h-full object-cover" loading="lazy" />
                                            <a href={photo.url} target="_blank" rel="noreferrer" className="absolute top-2 right-2 bg-card/90 p-2 rounded-full shadow-sm opacity-0 group-hover:opacity-100 transition-opacity"><ExternalLink className="w-4 h-4"/></a>
                                            {canEdit && (
                                              <button
                                                onClick={(e) => { e.stopPropagation(); handleDeletePhoto(photo.url, idx); }}
                                                disabled={isDeletingPhoto === idx}
                                                className="absolute top-2 left-2 bg-destructive/90 hover:bg-destructive text-white p-1.5 rounded-full shadow-sm opacity-0 group-hover:opacity-100 transition-opacity disabled:opacity-50"
                                                title="Delete photo"
                                              >
                                                {isDeletingPhoto === idx ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Trash2 className="w-3.5 h-3.5" />}
                                              </button>
                                            )}
                                        </div>
                                        {photo.timestamp && <p className="text-[10px] text-muted-foreground text-center">{formatPhotoTimestamp(photo.timestamp)}</p>}
                                    </div>
                                ))}
                            </div>
                        )}
                        {canEdit && (
                            <div className={cn("border-2 border-dashed rounded-lg p-6 flex flex-col items-center justify-center transition-colors text-center cursor-pointer", dragActive ? "border-primary bg-primary/5" : "border-border hover:border-primary/50", isUploadingPhotos && "opacity-50 pointer-events-none")} onDragEnter={handleDrag} onDragLeave={handleDrag} onDragOver={handleDrag} onDrop={handleDrop} onClick={() => !isUploadingPhotos && fileInputRef.current?.click()}>
                                <input ref={fileInputRef} type="file" multiple accept="image/*" onChange={handleFileSelect} className="hidden" />
                                {isUploadingPhotos ? <Loader2 className="w-8 h-8 text-primary animate-spin mb-2" /> : <ImagePlus className="w-8 h-8 text-muted-foreground mb-2" />}
                                <p className="text-sm font-medium">{isUploadingPhotos ? 'Uploading photos...' : 'Click to upload or drag & drop'}</p>
                            </div>
                        )}
                    </div>
                </TabsContent>

                <TabsContent value="responses" className="py-4 space-y-4 min-h-[300px]">
                    <div className="flex justify-between items-center">
                        <h4 className="text-sm font-semibold">Homeowner Responses</h4>
                        <Button size="sm" variant="outline" onClick={fetchResponses} disabled={loadingResponses}>
                          {loadingResponses ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : 'Refresh'}
                        </Button>
                    </div>
                    {loadingResponses ? (
                        <div className="flex justify-center py-12"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>
                    ) : responses.length === 0 ? (
                        <div className="text-center py-12 text-muted-foreground">
                            <MessageSquare className="w-10 h-10 mx-auto mb-3 opacity-30" />
                            <p className="text-sm">No responses submitted yet.</p>
                            <p className="text-xs mt-1">Homeowners can respond via the QR code on the violation notice.</p>
                        </div>
                    ) : (
                        <div className="space-y-3">
                            {responses.map((r) => (
                                <div key={r.id} className="rounded-lg border bg-muted/30 p-4 space-y-3">
                                    <div className="flex items-start justify-between">
                                        <div className="flex items-center gap-2">
                                            <User className="w-4 h-4 text-muted-foreground" />
                                            <span className="text-sm font-medium">{r.respondent_name || 'Anonymous'}</span>
                                        </div>
                                        <span className="text-xs text-muted-foreground">{formatDateTimeShortEST(r.created_at)}</span>
                                    </div>
                                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs">
                                        {r.respondent_email && (
                                            <div><span className="text-muted-foreground">Email:</span> <span className="font-medium">{r.respondent_email}</span></div>
                                        )}
                                        {r.respondent_phone && (
                                            <div><span className="text-muted-foreground">Phone:</span> <span className="font-medium">{r.respondent_phone}</span></div>
                                        )}
                                        {r.date_corrected && (
                                            <div><span className="text-muted-foreground">Date Corrected:</span> <span className="font-medium">{formatShortDateEST(r.date_corrected)}</span></div>
                                        )}
                                    </div>
                                    {r.response_text && (
                                        <div className="bg-background rounded-md border p-3 text-sm whitespace-pre-wrap">{r.response_text}</div>
                                    )}
                                    <Badge variant={r.status === 'reviewed' ? 'default' : 'secondary'} className="text-[10px]">{r.status || 'pending'}</Badge>
                                </div>
                            ))}
                        </div>
                    )}
                </TabsContent>

                <TabsContent value="timeline" className="py-4 space-y-4 min-h-[300px]">
                    <div className="flex justify-between items-center mb-4">
                        <h4 className="text-sm font-semibold">Activity History</h4>
                        <div className="flex gap-2">
                            <ViolationTimelineExportButton violation={violation} entries={timelineEntries} />
                            {canEdit && (
                                <>
                                    <Button size="sm" variant="outline" onClick={() => setIsMergeDialogOpen(true)}><GitMerge className="w-4 h-4 mr-2" /> Merge</Button>
                                    <Button size="sm" variant="outline" onClick={() => setIsImportDialogOpen(true)}><Upload className="w-4 h-4 mr-2" /> Import</Button>
                                    <Button size="sm" variant="outline" onClick={() => { setEditingEntry(null); setIsEntryDialogOpen(true); }}><Pencil className="w-4 h-4 mr-2" /> Add Entry</Button>
                                </>
                            )}
                        </div>
                    </div>
                    <ViolationTimelineManager entries={timelineEntries} onEdit={(entry) => { setEditingEntry(entry); setIsEntryDialogOpen(true); }} onDelete={deleteEntry} />
                </TabsContent>
            </Tabs>
        </div>

        <DialogFooter className="p-6 border-t bg-muted/30 sm:justify-between gap-2 shrink-0">
           <div className="flex gap-2 w-full sm:w-auto">
             <Button variant="outline" onClick={() => onOpenChange(false)}>Close</Button>
             {onEdit && canEdit && (<Button variant="secondary" onClick={onEdit}><Pencil className="w-4 h-4 mr-2" /> Edit Record</Button>)}
           </div>
           <div className="flex gap-2 w-full sm:w-auto">
             {onEmailNotice && canEdit && violation.owners?.electronic_consent && violation.owners?.email && (
               <Button variant="outline" onClick={() => { onOpenChange(false); onEmailNotice(violation); }}>
                 <Mail className="w-4 h-4 mr-2" /> Email Notice
               </Button>
             )}
             {onRegenerateNotice && canEdit && (
               <Button variant="outline" onClick={() => { onOpenChange(false); onRegenerateNotice(violation); }}>
                 <FileText className="w-4 h-4 mr-2" /> Regenerate Notice
               </Button>
             )}
             {activeTab === 'details' && (<Button onClick={() => setActiveTab('timeline')} className="w-full sm:w-auto">View Timeline <ArrowRight className="w-4 h-4 ml-2" /></Button>)}
           </div>
        </DialogFooter>

        <ViolationTimelineEntryDialog open={isEntryDialogOpen} onOpenChange={setIsEntryDialogOpen} entry={editingEntry} onSave={handleSaveTimelineEntry} loading={timelineLoading} />
        <ViolationTimelineImportDialog open={isImportDialogOpen} onOpenChange={setIsImportDialogOpen} preSelectedViolationId={violation.id} onSuccess={() => { if (onUpdate) onUpdate(); }} />
        <ViolationMergeDialog open={isMergeDialogOpen} onOpenChange={setIsMergeDialogOpen} violation={violation} onSuccess={() => { if (onUpdate) onUpdate(); }} />
      </DialogContent>
    </Dialog>
  );
}
