import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { AlertTriangle, Calendar, MapPin, Camera, History, FileText } from "lucide-react";
import { format } from "date-fns";
import { parseLocalDate } from "@/lib/dateUtils";
import type { Tables, Json } from "@/integrations/supabase/types";

interface Props {
  violation: Tables<"violations"> | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export default function ClientViolationDetailDialog({ violation, open, onOpenChange }: Props) {
  if (!violation) return null;

  const statusColor = (s: string | null) => {
    switch (s) {
      case "open": case "escalated": return "destructive" as const;
      case "resolved": case "closed": return "default" as const;
      default: return "secondary" as const;
    }
  };

  const photoUrls = Array.isArray(violation.photo_urls)
    ? (violation.photo_urls as string[])
    : violation.photo_url
    ? [violation.photo_url]
    : [];

  const timelineEntries = Array.isArray(violation.timeline_entries)
    ? (violation.timeline_entries as Record<string, unknown>[])
    : [];

  const noticeHistory = Array.isArray(violation.notice_history)
    ? (violation.notice_history as Record<string, unknown>[])
    : [];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-destructive" />
            {violation.title}
          </DialogTitle>
        </DialogHeader>

        <Tabs defaultValue="details" className="mt-2">
          <TabsList>
            <TabsTrigger value="details"><FileText className="w-4 h-4 mr-1" />Details</TabsTrigger>
            <TabsTrigger value="timeline"><History className="w-4 h-4 mr-1" />Timeline ({timelineEntries.length})</TabsTrigger>
            <TabsTrigger value="photos"><Camera className="w-4 h-4 mr-1" />Photos ({photoUrls.length})</TabsTrigger>
          </TabsList>

          <TabsContent value="details" className="space-y-4 mt-4">
            <div className="grid grid-cols-2 gap-4">
              <Detail label="Status"><Badge variant={statusColor(violation.status)}>{violation.status || "open"}</Badge></Detail>
              <Detail label="Priority"><span className="font-medium capitalize">{violation.priority || "—"}</span></Detail>
              <Detail label="Stage">{violation.stage || violation.notice_level || "—"}</Detail>
              <Detail label="Category">{violation.violation_type || violation.category || "—"}</Detail>
              <Detail label="Date Reported">
                <span className="flex items-center gap-1">
                  <Calendar className="w-3.5 h-3.5" />
                  {violation.violation_date ? format(parseLocalDate(violation.violation_date), "MMMM d, yyyy") : violation.created_at ? format(new Date(violation.created_at), "MMMM d, yyyy") : "—"}
                </span>
              </Detail>
              <Detail label="Due Date">
                {violation.due_date ? format(parseLocalDate(violation.due_date), "MMMM d, yyyy") : "None"}
              </Detail>
              {violation.address && (
                <Detail label="Address" className="col-span-2">
                  <span className="flex items-center gap-1"><MapPin className="w-3.5 h-3.5" />{violation.address}</span>
                </Detail>
              )}
            </div>
            {(violation.description || violation.notes) && (
              <div>
                <p className="text-sm text-muted-foreground mb-1">Description / Notes</p>
                <p className="bg-muted p-3 rounded-md border text-sm">{violation.description || violation.notes || "No description provided."}</p>
              </div>
            )}

            {noticeHistory.length > 0 && (
              <div>
                <p className="text-sm text-muted-foreground mb-2">Notice History</p>
                <div className="space-y-2">
                  {noticeHistory.map((entry: any, idx: number) => (
                    <div key={idx} className="bg-muted/50 p-3 rounded border text-sm">
                      <div className="flex justify-between">
                        <span className="font-medium">{entry.stage || entry.notice_level || `Notice ${idx + 1}`}</span>
                        {entry.date && <span className="text-muted-foreground">{format(new Date(entry.date), "MMM d, yyyy")}</span>}
                      </div>
                      {entry.requested_action && <p className="mt-1 text-muted-foreground">{entry.requested_action}</p>}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </TabsContent>

          <TabsContent value="timeline" className="mt-4">
            {timelineEntries.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <History className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No timeline entries yet.</p>
              </div>
            ) : (
              <div className="space-y-3">
                {timelineEntries.map((entry: any, idx: number) => (
                  <div key={entry.id || idx} className="border rounded-lg p-3">
                    <div className="flex justify-between items-start">
                      <div>
                        <Badge variant="outline" className="mb-1">{entry.status || entry.action || "update"}</Badge>
                        <p className="text-sm mt-1">{entry.description || entry.details || "No description"}</p>
                      </div>
                      <span className="text-xs text-muted-foreground whitespace-nowrap ml-2">
                        {entry.date || entry.created_at ? format(new Date((entry.date || entry.created_at) as string), "MMM d, yyyy") : "—"}
                      </span>
                    </div>
                    {(entry.recorded_by_name || entry.metadata?.performed_by_name) && (
                      <p className="text-xs text-muted-foreground mt-2">By: {(entry.recorded_by_name || entry.metadata?.performed_by_name) as string}</p>
                    )}
                  </div>
                ))}
              </div>
            )}
          </TabsContent>

          <TabsContent value="photos" className="mt-4">
            {photoUrls.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Camera className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No photos attached.</p>
              </div>
            ) : (
              <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                {photoUrls.map((url, idx) => (
                  <a key={idx} href={url} target="_blank" rel="noopener noreferrer" className="block">
                    <img src={url} alt={`Evidence ${idx + 1}`} className="rounded-lg border object-cover w-full h-40 hover:opacity-80 transition-opacity" />
                  </a>
                ))}
              </div>
            )}
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}

function Detail({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {
  return (
    <div className={className}>
      <p className="text-sm text-muted-foreground">{label}</p>
      <div className="font-medium mt-0.5">{children}</div>
    </div>
  );
}
