import { useEffect, useState } from "react";
import { format } from "date-fns";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ShieldAlert, AlertCircle, Calendar, MapPin, FileText } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { useToast } from "@/hooks/use-toast";
import { parseLocalDate } from "@/lib/dateUtils";

interface Violation {
  id: string;
  title: string;
  description: string | null;
  category: string | null;
  violation_type: string | null;
  status: string | null;
  priority: string | null;
  stage: string | null;
  notice_level: string | null;
  address: string | null;
  violation_date: string | null;
  due_date: string | null;
  resolved_date: string | null;
  created_at: string;
  photo_url: string | null;
  photo_urls: any;
}

const statusVariant = (status: string | null) => {
  const s = (status || "").toLowerCase();
  if (s === "resolved" || s === "closed") return "default" as const;
  if (s === "open" || s === "active") return "destructive" as const;
  return "secondary" as const;
};

const priorityVariant = (priority: string | null) => {
  const p = (priority || "").toLowerCase();
  if (p === "high" || p === "urgent") return "destructive" as const;
  if (p === "medium") return "secondary" as const;
  return "outline" as const;
};

export default function HomeownerViolationsPage() {
  const { currentOwner, unit, loading: contextLoading } = useHomeowner();
  const { toast } = useToast();
  const [violations, setViolations] = useState<Violation[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (contextLoading) return;
    if (!currentOwner) {
      setViolations([]);
      setLoading(false);
      return;
    }

    const fetchViolations = async () => {
      setLoading(true);
      const query = supabase
        .from("violations")
        .select(
          "id, title, description, category, violation_type, status, priority, stage, notice_level, address, violation_date, due_date, resolved_date, created_at, photo_url, photo_urls"
        )
        .order("created_at", { ascending: false });

      const { data, error } = await (unit?.id
        ? query.eq("unit_id", unit.id)
        : query.eq("owner_id", currentOwner.id));

      if (error) {
        toast({ variant: "destructive", title: "Could not load violations", description: error.message });
        setViolations([]);
      } else {
        setViolations(data || []);
      }
      setLoading(false);
    };

    fetchViolations();
  }, [contextLoading, currentOwner, unit?.id, toast]);

  if (contextLoading || loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  if (!currentOwner) {
    return (
      <div className="text-center py-20 space-y-2">
        <AlertCircle className="h-10 w-10 text-muted-foreground/30 mx-auto" />
        <p className="text-lg font-medium text-foreground">No property linked to your account</p>
        <p className="text-sm text-muted-foreground">Please contact your property management company.</p>
      </div>
    );
  }

  const openCount = violations.filter((v) => {
    const s = (v.status || "").toLowerCase();
    return s !== "resolved" && s !== "closed";
  }).length;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
          <ShieldAlert className="w-6 h-6 text-primary" /> Violations
        </h1>
        <p className="text-muted-foreground mt-1">
          Compliance notices recorded for your property.
          {openCount > 0 && (
            <span className="ml-2 inline-flex items-center gap-1 text-warning font-medium">
              · {openCount} open
            </span>
          )}
        </p>
      </div>

      {violations.length === 0 ? (
        <Card>
          <CardContent className="p-12 text-center flex flex-col items-center">
            <div className="bg-muted p-4 rounded-full mb-3">
              <ShieldAlert className="w-8 h-8 text-muted-foreground" />
            </div>
            <p className="text-foreground font-medium">No violations on file</p>
            <p className="text-sm text-muted-foreground mt-1">
              Your property has no recorded compliance issues. Thank you for being a great neighbor!
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {violations.map((v) => {
            const photos: string[] = Array.isArray(v.photo_urls)
              ? (v.photo_urls as string[])
              : v.photo_url
              ? [v.photo_url]
              : [];
            return (
              <Card key={v.id}>
                <CardHeader className="pb-3">
                  <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
                    <div className="space-y-1">
                      <CardTitle className="text-lg">{v.title || v.violation_type || "Violation"}</CardTitle>
                      <CardDescription className="flex flex-wrap items-center gap-2 text-xs">
                        {v.category && <span>{v.category}</span>}
                        {v.address && (
                          <span className="flex items-center gap-1">
                            <MapPin className="w-3 h-3" /> {v.address}
                          </span>
                        )}
                        {v.violation_date && (
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" /> Issued{" "}
                            {format(parseLocalDate(v.violation_date), "MMM d, yyyy")}
                          </span>
                        )}
                      </CardDescription>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      <Badge variant={statusVariant(v.status)}>{v.status || "Open"}</Badge>
                      {v.priority && <Badge variant={priorityVariant(v.priority)}>{v.priority}</Badge>}
                      {v.notice_level && <Badge variant="outline">{v.notice_level}</Badge>}
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-3">
                  {v.description && <p className="text-sm text-foreground whitespace-pre-wrap">{v.description}</p>}

                  <div className="flex flex-wrap gap-x-6 gap-y-1 text-xs text-muted-foreground">
                    {v.due_date && (
                      <span>
                        <strong className="text-foreground">Due:</strong>{" "}
                        {format(parseLocalDate(v.due_date), "MMM d, yyyy")}
                      </span>
                    )}
                    {v.resolved_date && (
                      <span>
                        <strong className="text-foreground">Resolved:</strong>{" "}
                        {format(parseLocalDate(v.resolved_date), "MMM d, yyyy")}
                      </span>
                    )}
                    {v.stage && (
                      <span>
                        <strong className="text-foreground">Stage:</strong> {v.stage}
                      </span>
                    )}
                  </div>

                  {photos.length > 0 && (
                    <div className="flex flex-wrap gap-2 pt-2">
                      {photos.map((url, idx) => (
                        <a
                          key={idx}
                          href={url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="block w-24 h-24 rounded-md overflow-hidden border border-border hover:opacity-80 transition"
                        >
                          <img src={url} alt={`Violation photo ${idx + 1}`} className="w-full h-full object-cover" />
                        </a>
                      ))}
                    </div>
                  )}

                  {!v.description && photos.length === 0 && (
                    <p className="text-xs text-muted-foreground flex items-center gap-1">
                      <FileText className="w-3 h-3" /> No additional details provided.
                    </p>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
