import { useState, useEffect, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { PieChart, AlertTriangle, TrendingUp, Clock, CheckCircle, Loader2 } from "lucide-react";
import { format, subMonths, isAfter } from "date-fns";
import type { Tables } from "@/integrations/supabase/types";

export default function ClientViolationReportsPage() {
  const [violations, setViolations] = useState<Tables<"violations">[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetch = async () => {
      const { data } = await supabase
        .from("violations")
        .select("*")
        .order("created_at", { ascending: false });
      setViolations(data || []);
      setLoading(false);
    };
    fetch();
  }, []);

  const stats = useMemo(() => {
    const total = violations.length;
    const open = violations.filter(v => v.status === "open" || v.status === "escalated" || v.status === "recommended_for_fining").length;
    const escalated = violations.filter(v => v.status === "escalated").length;
    const resolved = violations.filter(v => v.status === "resolved" || v.status === "closed").length;
    const pending = violations.filter(v => v.status === "pending").length;

    const sixMonthsAgo = subMonths(new Date(), 6);
    const recent = violations.filter(v => isAfter(new Date(v.created_at), sixMonthsAgo)).length;

    // By category
    const byCategory: Record<string, number> = {};
    violations.forEach(v => {
      const cat = v.violation_type || v.category || "Uncategorized";
      byCategory[cat] = (byCategory[cat] || 0) + 1;
    });

    // By priority
    const byPriority: Record<string, number> = {};
    violations.forEach(v => {
      const p = v.priority || "unset";
      byPriority[p] = (byPriority[p] || 0) + 1;
    });

    // By month (last 6 months)
    const byMonth: Record<string, number> = {};
    violations.forEach(v => {
      const d = new Date(v.created_at);
      if (isAfter(d, sixMonthsAgo)) {
        const key = format(d, "MMM yyyy");
        byMonth[key] = (byMonth[key] || 0) + 1;
      }
    });

    return { total, open, escalated, resolved, pending, recent, byCategory, byPriority, byMonth };
  }, [violations]);

  if (loading) {
    return (
      <div className="flex justify-center py-12"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div>
    );
  }

  if (violations.length === 0) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-3xl font-bold text-foreground flex items-center gap-2">
            <PieChart className="w-7 h-7" /> Violation Reports
          </h1>
          <p className="text-muted-foreground">View analytics and reports for your property violations.</p>
        </div>
        <Card className="p-12 text-center text-muted-foreground bg-muted/50">
          <PieChart className="h-8 w-8 mx-auto mb-3 text-muted-foreground/50" />
          <p>No violations found for your account.</p>
        </Card>
      </div>
    );
  }

  const sortedCategories = Object.entries(stats.byCategory).sort((a, b) => b[1] - a[1]);
  const sortedMonths = Object.entries(stats.byMonth);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground flex items-center gap-2">
          <PieChart className="w-7 h-7" /> Violation Reports
        </h1>
        <p className="text-muted-foreground">Analytics and summary statistics for violations.</p>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard icon={AlertTriangle} label="Total" value={stats.total} color="text-foreground" />
        <StatCard icon={Clock} label="Open" value={stats.open} color="text-destructive" />
        <StatCard icon={TrendingUp} label="Escalated" value={stats.escalated} color="text-destructive" />
        <StatCard icon={CheckCircle} label="Resolved" value={stats.resolved} color="text-primary" />
      </div>

      <div className="grid md:grid-cols-2 gap-6">
        {/* By Category */}
        <Card>
          <CardHeader><CardTitle className="text-base">By Category</CardTitle></CardHeader>
          <CardContent className="space-y-2">
            {sortedCategories.map(([cat, count]) => (
              <div key={cat} className="flex justify-between items-center">
                <span className="text-sm">{cat}</span>
                <div className="flex items-center gap-2">
                  <div className="h-2 bg-primary/20 rounded-full w-24">
                    <div
                      className="h-2 bg-primary rounded-full"
                      style={{ width: `${Math.round((count / stats.total) * 100)}%` }}
                    />
                  </div>
                  <span className="text-sm font-medium w-8 text-right">{count}</span>
                </div>
              </div>
            ))}
          </CardContent>
        </Card>

        {/* By Priority */}
        <Card>
          <CardHeader><CardTitle className="text-base">By Priority</CardTitle></CardHeader>
          <CardContent className="space-y-3">
            {["critical", "high", "medium", "low"].map(p => {
              const count = stats.byPriority[p] || 0;
              if (count === 0) return null;
              return (
                <div key={p} className="flex justify-between items-center">
                  <Badge variant={p === "critical" || p === "high" ? "destructive" : "secondary"} className="capitalize">{p}</Badge>
                  <span className="font-medium">{count}</span>
                </div>
              );
            })}
          </CardContent>
        </Card>

        {/* Monthly Trend */}
        {sortedMonths.length > 0 && (
          <Card className="md:col-span-2">
            <CardHeader><CardTitle className="text-base">Monthly Trend (Last 6 Months)</CardTitle></CardHeader>
            <CardContent>
              <div className="flex items-end gap-3 h-32">
                {sortedMonths.map(([month, count]) => {
                  const maxCount = Math.max(...sortedMonths.map(([, c]) => c));
                  const height = maxCount > 0 ? (count / maxCount) * 100 : 0;
                  return (
                    <div key={month} className="flex flex-col items-center flex-1">
                      <span className="text-xs font-medium mb-1">{count}</span>
                      <div className="w-full bg-primary/20 rounded-t" style={{ height: `${Math.max(height, 4)}%` }}>
                        <div className="w-full h-full bg-primary rounded-t" />
                      </div>
                      <span className="text-xs text-muted-foreground mt-1 truncate w-full text-center">{month.split(" ")[0]}</span>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}

function StatCard({ icon: Icon, label, value, color }: { icon: any; label: string; value: number; color: string }) {
  return (
    <Card>
      <CardContent className="pt-6">
        <div className="flex items-center gap-3">
          <Icon className={`w-5 h-5 ${color}`} />
          <div>
            <p className="text-2xl font-bold">{value}</p>
            <p className="text-sm text-muted-foreground">{label}</p>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
