import React, { useState } from 'react';
import { logStatusChange } from '@/lib/violationTimelineLogger';
import { motion } from 'framer-motion';
import { Calendar, MapPin, Camera, User, MoreHorizontal, CheckCircle, Ban, AlertCircle, MessageSquare, Clock, Trash2, ImageOff, TrendingUp, BookOpen, AlertTriangle } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from '@/components/ui/dropdown-menu';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';
import { cn } from '@/lib/utils';
import { useCommentCount } from '@/hooks/useCommentCount';
import { getNoticeColor, isValidStatus, VALID_STATUSES } from '@/lib/ViolationNoticeProgressionHelper';
import { formatPhotoTimestamp } from '@/lib/exifUtils';

const parseDateSafe = (dateString) => {
    if (!dateString) return null;
    if (typeof dateString === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
        return new Date(`${dateString}T12:00:00`);
    }
    return new Date(dateString);
};

const formatViolationDate = (dateString) => {
    if (!dateString) return 'N/A';
    return parseDateSafe(dateString).toLocaleDateString('en-US', {
        month: 'short', day: 'numeric', year: 'numeric'
    });
};

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

const ViolationCard = ({ violation, onStatusChange, isSelected, onSelect, showSelection, canEdit = true }) => {
  const navigate = useNavigate();
  const { toast } = useToast();
  const [isUpdateDialogOpen, setIsUpdateDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [pendingStatus, setPendingStatus] = useState(null);
  const [isLightboxOpen, setIsLightboxOpen] = useState(false);
  const [lightboxIndex, setLightboxIndex] = useState(0);

  const { count: commentCount, loading: countLoading } = useCommentCount(violation?.id, 'violation');
  
  const statusConfig = {
    open: { color: 'bg-red-100 text-red-700 border-red-200', label: 'Open', icon: AlertCircle },
    resolved: { color: 'bg-green-100 text-green-700 border-green-200', label: 'Resolved', icon: CheckCircle },
    fined: { color: 'bg-blue-100 text-blue-700 border-blue-200', label: 'Fined', icon: Ban },
    escalated: { color: 'bg-purple-100 text-purple-700 border-purple-200', label: 'Escalated', icon: TrendingUp },
    closed: { color: 'bg-gray-100 text-gray-700 border-gray-200', label: 'Closed', icon: CheckCircle },
    pending: { color: 'bg-yellow-100 text-yellow-700 border-yellow-200', label: 'Pending', icon: Clock }
  };

  const currentStatus = violation.status?.toLowerCase() || 'open';
  const statusStyle = statusConfig[currentStatus] || statusConfig.open;
  const stage = violation.stage || violation.notice_level || 'First Notice';

  const history = violation.notice_history || [];
  const latestHistory = history.length > 0 ? history[history.length - 1] : {};

  const articleSection = latestHistory.article_section || violation.article || null;
  const requestedAction = violation.description || latestHistory.requested_action || null;

  const daysUntilDue = violation.due_date 
    ? Math.ceil((parseDateSafe(violation.due_date) - new Date()) / (1000 * 60 * 60 * 24)) 
    : null;
  const dueStatusColor = daysUntilDue < 0 ? 'text-red-600' : daysUntilDue <= 3 ? 'text-orange-600' : 'text-slate-500';

  const initiateStatusUpdate = (newStatus, e) => {
    e.stopPropagation();
    setPendingStatus(newStatus);
    setIsUpdateDialogOpen(true);
  };

  const confirmStatusUpdate = async () => {
    if (!pendingStatus) return;
    if (!isValidStatus(pendingStatus)) {
      toast({ variant: "destructive", title: "Invalid Status", description: `Status '${pendingStatus}' is not valid.` });
      setIsUpdateDialogOpen(false);
      setPendingStatus(null);
      return;
    }
    try {
      const previousStatus = violation.status;
      const { error } = await supabase.from('violations').update({ status: pendingStatus }).eq('id', violation.id);
      if (error) throw error;
      await logStatusChange(violation.id, previousStatus, pendingStatus);
      toast({ title: "Status Updated", description: `Violation marked as ${pendingStatus}.` });
      if (onStatusChange) onStatusChange();
    } catch (error) {
      toast({ variant: "destructive", title: "Error", description: "Failed to update status." });
    } finally {
      setIsUpdateDialogOpen(false);
      setPendingStatus(null);
    }
  };

  const handleDelete = async () => {
    try {
      const { error } = await supabase.from('violations').delete().eq('id', violation.id);
      if (error) throw error;
      toast({ title: "Violation Deleted", description: "The violation has been successfully removed." });
      if (onStatusChange) onStatusChange();
    } catch (error) {
      toast({ variant: "destructive", title: "Error", description: "Failed to delete violation." });
    } finally {
      setIsDeleteDialogOpen(false);
    }
  };

  const handleCheckboxChange = (checked) => {
    if (onSelect) onSelect(violation.id, checked);
  };
  
  const normalizePhoto = (p) => typeof p === 'string' ? { url: p, timestamp: null } : p;
  const splitSemicolonUrls = (s) => s.split(/;\s*/).map(u => u.trim()).filter(Boolean);
  
  let allPhotos = [];
  if (violation.photo_urls && Array.isArray(violation.photo_urls) && violation.photo_urls.length > 0) {
      allPhotos = 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) {
      allPhotos = splitSemicolonUrls(violation.photo_url).map(u => ({ url: u, timestamp: null }));
  }

  const openLightbox = (e, index) => {
      e.stopPropagation();
      setLightboxIndex(index);
      setIsLightboxOpen(true);
  };

  return (
    <>
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        className={cn(
            "bg-card rounded-lg shadow-sm border p-4 flex flex-col justify-between hover:shadow-md transition-all duration-300 relative group min-h-[380px]",
            isSelected ? "border-primary bg-primary/5 ring-1 ring-primary" : "border-border"
        )}
      >
        {canEdit && showSelection && (
            <div className="absolute top-4 left-4 z-20" onClick={(e) => e.stopPropagation()}>
                <Checkbox checked={isSelected} onCheckedChange={handleCheckboxChange} className="h-5 w-5 border-2" />
            </div>
        )}

        {canEdit && (
            <div className="absolute top-4 right-4 z-10">
               <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                     <Button variant="ghost" size="icon" className="h-8 w-8 hover:bg-muted rounded-full">
                        <MoreHorizontal className="w-4 h-4 text-muted-foreground" />
                     </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                     {['open', 'resolved', 'recommended_for_fining', 'fined', 'escalated'].map(s => (
                         <DropdownMenuItem key={s} onClick={(e) => initiateStatusUpdate(s, e)} disabled={currentStatus === s} className="capitalize">
                            Mark as {s.replace(/_/g, ' ')}
                         </DropdownMenuItem>
                     ))}
                     <DropdownMenuSeparator />
                     <DropdownMenuItem 
                        className="text-destructive focus:text-destructive focus:bg-destructive/10" 
                        onClick={(e) => { e.stopPropagation(); setIsDeleteDialogOpen(true); }}
                     >
                        <Trash2 className="w-4 h-4 mr-2" /> Delete Violation
                     </DropdownMenuItem>
                  </DropdownMenuContent>
               </DropdownMenu>
            </div>
        )}

        <div className={cn(canEdit && showSelection && "pl-8")}>
          <div className="mb-4">
              <div className="flex flex-wrap gap-2 items-center mb-2 pr-8">
                  <span className={cn("px-2.5 py-0.5 text-xs font-semibold rounded-full border flex items-center w-fit", statusStyle.color)}>
                      <statusStyle.icon className="w-3 h-3 mr-1" /> {statusStyle.label}
                  </span>
                  <Badge className={cn("px-2 py-0.5 text-[10px] font-semibold border", getNoticeColor(stage))}>
                      {stage}
                  </Badge>
              </div>

              <h3 className="font-bold text-foreground text-base leading-tight mb-1">{violation.violation_type || violation.title}</h3>
              
              <div className="flex flex-col gap-1 mt-2">
                  <div className="flex items-center text-sm text-muted-foreground w-fit">
                    <MapPin className="w-3.5 h-3.5 mr-1.5 flex-shrink-0" />
                    <span className="truncate max-w-[200px] font-medium">{violation.owners?.property_address || violation.address || 'No address'}</span>
                  </div>
                  <div className="flex items-center text-xs text-muted-foreground">
                     <User className="w-3.5 h-3.5 mr-1.5" />
                     <span className="truncate max-w-[200px]">{getOwnerName(violation)}</span>
                  </div>
              </div>
          </div>

          <div className="space-y-2 mb-4 bg-muted/50 p-3 rounded-md border text-xs">
              {articleSection && (
                  <div className="flex gap-2">
                      <BookOpen className="w-3 h-3 text-muted-foreground mt-0.5 flex-shrink-0" />
                      <div><span className="font-semibold text-foreground mr-1">Article:</span><span className="text-muted-foreground">{articleSection}</span></div>
                  </div>
              )}
              {requestedAction && (
                  <div className="flex gap-2">
                      <AlertTriangle className="w-3 h-3 text-muted-foreground mt-0.5 flex-shrink-0" />
                      <div><span className="font-semibold text-foreground mr-1">Action:</span><span className="text-muted-foreground line-clamp-2">{requestedAction}</span></div>
                  </div>
              )}
          </div>

          {allPhotos.length > 0 && (
             <div className="mb-4">
                 <div className="flex flex-wrap gap-2">
                     {allPhotos.slice(0, 4).map((photo, idx) => (
                         <div key={idx} className="relative w-16 h-16 rounded-md overflow-hidden border cursor-pointer group/thumb hover:ring-2 ring-primary" onClick={(e) => openLightbox(e, idx)}>
                            <img src={photo.url} alt={`Evidence ${idx+1}`} className="w-full h-full object-cover" />
                            <div className="absolute inset-0 bg-black/0 group-hover/thumb:bg-black/20 transition-colors flex items-center justify-center">
                                <Camera className="w-4 h-4 text-white opacity-0 group-hover/thumb:opacity-100" />
                            </div>
                            {idx === 3 && allPhotos.length > 4 && (
                                <div className="absolute inset-0 bg-black/60 flex items-center justify-center text-white text-xs font-bold">+{allPhotos.length - 4}</div>
                            )}
                         </div>
                     ))}
                 </div>
             </div>
          )}
        </div>

        <div className="flex justify-between items-center text-xs text-muted-foreground mt-auto border-t pt-3">
          <div className="flex flex-col gap-0.5">
            <span className="flex items-center">
               <Calendar className="w-3.5 h-3.5 mr-1" />
               <span className="font-medium">Violation: {formatViolationDate(violation.violation_date || violation.created_at)}</span>
            </span>
            <span className="flex items-center">
               <Clock className="w-3.5 h-3.5 mr-1" />
               <span>Original: {formatViolationDate(violation.created_at)}</span>
            </span>
            <span className="flex items-center">
               <AlertCircle className="w-3.5 h-3.5 mr-1" />
               <span className={cn("font-medium", dueStatusColor)}>Due: {formatViolationDate(violation.due_date)}</span>
            </span>
          </div>
          {!countLoading && commentCount > 0 && (
              <Badge variant="secondary" className="px-1.5 py-0 h-5 text-[10px] flex items-center gap-1">
                  <MessageSquare className="w-2.5 h-2.5" /> {commentCount}
              </Badge>
          )}
        </div>
      </motion.div>

      <Dialog open={isLightboxOpen} onOpenChange={setIsLightboxOpen}>
         <DialogContent className="max-w-4xl p-0 overflow-hidden bg-black border-none flex flex-col items-center justify-center h-full max-h-[90vh]">
             {allPhotos[lightboxIndex] && (
                 <>
                    <img src={allPhotos[lightboxIndex].url} alt="Evidence Full" className="w-auto h-auto max-w-full max-h-[85vh] object-contain" />
                    {allPhotos[lightboxIndex].timestamp && (
                        <div className="w-full bg-black/80 text-white text-xs p-2 text-center">{formatPhotoTimestamp(allPhotos[lightboxIndex].timestamp)}</div>
                    )}
                 </>
             )}
         </DialogContent>
      </Dialog>

      <AlertDialog open={isUpdateDialogOpen} onOpenChange={setIsUpdateDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader><AlertDialogTitle>Update Status</AlertDialogTitle><AlertDialogDescription>Change status to <strong>{pendingStatus}</strong>?</AlertDialogDescription></AlertDialogHeader>
          <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={confirmStatusUpdate}>Confirm</AlertDialogAction></AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader><AlertDialogTitle>Delete Violation</AlertDialogTitle><AlertDialogDescription>Are you sure? This action cannot be undone.</AlertDialogDescription></AlertDialogHeader>
          <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90">Delete</AlertDialogAction></AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default ViolationCard;
