import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Shield, TrendingUp, Layers, CalendarClock, Activity, FileText, ShieldAlert, DollarSign, Users } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { formatShortDateEST } from "@/lib/timezoneUtils";

interface Props {
  cardId: string;
}

export default function ChartWidget({ cardId }: Props) {
  if (cardId === "chart_community_health") return <CommunityHealthWidget />;
  if (cardId === "chart_recent_activity") return <RecentActivityWidget />;
  return <div className="p-4 text-muted-foreground text-sm">Unknown chart</div>;
}

function CommunityHealthWidget() {
  const [data, setData] = useState({ compliance: 0, delinquency: 0, projects: 0, reminders: 0 });

  useEffect(() => {
    Promise.all([
      supabase.from("owners").select("id", { count: "exact", head: true }).eq("status", "active"),
      supabase.from("violations").select("id", { count: "exact", head: true }).eq("status", "open"),
      supabase.from("units").select("id", { count: "exact", head: true }).eq("status", "delinquent"),
      supabase.from("projects").select("id", { count: "exact", head: true }).neq("status", "completed"),
      supabase.from("reminders").select("id", { count: "exact", head: true }).neq("status", "dismissed"),
    ]).then(([owners, violations, units, projects, reminders]) => {
      const total = owners.count || 1;
      setData({
        compliance: Math.round(((total - (violations.count || 0)) / total) * 100),
        delinquency: Math.round(((units.count || 0) / total) * 100),
        projects: projects.count || 0,
        reminders: reminders.count || 0,
      });
    });
  }, []);

  const metrics = [
    { label: "Compliance Rate", value: `${data.compliance}%`, icon: <Shield className="w-4 h-4 text-emerald-600" />, bg: "bg-emerald-50" },
    { label: "Delinquency Rate", value: `${data.delinquency}%`, icon: <TrendingUp className="w-4 h-4 text-amber-600" />, bg: "bg-amber-50" },
    { label: "Active Projects", value: String(data.projects), icon: <Layers className="w-4 h-4 text-primary" />, bg: "bg-primary/10" },
    { label: "Upcoming Deadlines", value: String(data.reminders), icon: <CalendarClock className="w-4 h-4 text-purple-600" />, bg: "bg-purple-50" },
  ];

  return (
    <div className="h-full flex flex-col">
      <div className="px-4 pt-4 pb-2">
        <div className="flex items-center gap-2 text-[15px] font-semibold">
          <Shield className="h-4 w-4 text-primary" /> Community Health
        </div>
        <p className="text-xs text-muted-foreground">Key performance indicators</p>
      </div>
      <div className="px-4 pb-4 grid grid-cols-2 gap-3 flex-1">
        {metrics.map((m) => (
          <div key={m.label} className="flex items-center gap-3 rounded-lg border bg-card p-3">
            <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${m.bg}`}>{m.icon}</div>
            <div>
              <p className="text-lg font-semibold leading-none">{m.value}</p>
              <p className="text-[11px] text-muted-foreground mt-0.5">{m.label}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function RecentActivityWidget() {
  const [entries, setEntries] = useState<{ text: string; time: string; icon: React.ReactNode }[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchActivity = async () => {
      const now = new Date();
      const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString();

      const [violations, arcApps, payments, requests, announcements] = await Promise.all([
        supabase.from("violations").select("id, title, category, created_at").gte("created_at", thirtyDaysAgo).order("created_at", { ascending: false }).limit(5),
        supabase.from("arc_applications").select("id, title, created_at").gte("created_at", thirtyDaysAgo).order("created_at", { ascending: false }).limit(5),
        supabase.from("admin_payments").select("id, description, amount, created_at").gte("created_at", thirtyDaysAgo).order("created_at", { ascending: false }).limit(5),
        supabase.from("homeowner_requests").select("id, title, created_at").gte("created_at", thirtyDaysAgo).order("created_at", { ascending: false }).limit(5),
        supabase.from("announcements").select("id, title, created_at").gte("created_at", thirtyDaysAgo).order("created_at", { ascending: false }).limit(5),
      ]);

      const items: { text: string; time: string; sortDate: string; icon: React.ReactNode }[] = [];

      (violations.data || []).forEach((v) => items.push({
        text: `Violation: ${v.category || v.title || "Notice"}`,
        time: formatRelativeTime(v.created_at),
        sortDate: v.created_at,
        icon: <ShieldAlert className="w-3.5 h-3.5 text-destructive" />,
      }));
      (arcApps.data || []).forEach((a) => items.push({
        text: `ARC: ${a.title}`,
        time: formatRelativeTime(a.created_at),
        sortDate: a.created_at,
        icon: <FileText className="w-3.5 h-3.5 text-primary" />,
      }));
      (payments.data || []).forEach((p) => items.push({
        text: `Payment: $${p.amount.toFixed(2)}`,
        time: formatRelativeTime(p.created_at),
        sortDate: p.created_at,
        icon: <DollarSign className="w-3.5 h-3.5 text-emerald-600" />,
      }));
      (requests.data || []).forEach((r: any) => items.push({
        text: `Request: ${r.title || "New request"}`,
        time: formatRelativeTime(r.created_at),
        sortDate: r.created_at,
        icon: <Users className="w-3.5 h-3.5 text-muted-foreground" />,
      }));
      (announcements.data || []).forEach((a) => items.push({
        text: `Announcement: ${a.title}`,
        time: formatRelativeTime(a.created_at),
        sortDate: a.created_at,
        icon: <Activity className="w-3.5 h-3.5 text-amber-600" />,
      }));

      items.sort((a, b) => new Date(b.sortDate).getTime() - new Date(a.sortDate).getTime());
      setEntries(items.slice(0, 8).map(({ text, time, icon }) => ({ text, time, icon })));
      setLoading(false);
    };

    fetchActivity();
  }, []);

  return (
    <div className="h-full flex flex-col">
      <div className="px-4 pt-4 pb-2">
        <div className="flex items-center gap-2 text-[15px] font-semibold">
          <Activity className="h-4 w-4 text-primary" /> Recent Activity
        </div>
        <p className="text-xs text-muted-foreground">Latest events across associations</p>
      </div>
      {loading ? (
        <div className="flex-1 flex items-center justify-center">
          <div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
        </div>
      ) : entries.length === 0 ? (
        <div className="flex-1 flex items-center justify-center text-sm text-muted-foreground">No recent activity</div>
      ) : (
        <div className="divide-y divide-border flex-1 overflow-auto">
          {entries.map((entry, i) => (
            <div key={i} className="flex items-center gap-3 px-4 py-2.5 hover:bg-muted/50 transition-colors">
              <div className="flex h-7 w-7 items-center justify-center rounded-full bg-muted/80">{entry.icon}</div>
              <div className="flex-1 min-w-0">
                <p className="text-[13px] font-medium text-foreground truncate">{entry.text}</p>
              </div>
              <span className="text-[11px] text-muted-foreground shrink-0">{entry.time}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function formatRelativeTime(dateStr: string): string {
  const now = new Date();
  const date = new Date(dateStr);
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  if (diffMins < 1) return "Just now";
  if (diffMins < 60) return `${diffMins}m ago`;
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return `${diffHours}h ago`;
  const diffDays = Math.floor(diffHours / 24);
  if (diffDays < 7) return `${diffDays}d ago`;
  return formatShortDateEST(dateStr);
}
