import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import {
  FileText, ShieldAlert, TrendingUp, Clock, ArrowRight, ArrowUpRight,
  Plus, CheckSquare, FolderOpen, Bell, Megaphone, MessageCircle,
  PieChart as PieChartIcon, DollarSign, BarChart3, Users,
  Activity, Shield, CalendarClock, Layers
} from "lucide-react";
import { StripeTransactionsCard } from "./StripeTransactionsCard";
import { FormInboxCard } from "./FormInboxCard";
import { AutopayManagementCard } from "./AutopayManagementCard";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { format, isPast, isToday, isTomorrow } from "date-fns";
import { htmlToPlainText } from "@/lib/htmlTextUtils";

const priorityColors: Record<string, string> = {
  high: "cc-badge-danger",
  medium: "cc-badge-warning",
  low: "cc-badge-info",
};

const statusColors: Record<string, string> = {
  active: "cc-badge-success",
  pending: "cc-badge-warning",
  completed: "cc-badge-neutral",
  overdue: "cc-badge-danger",
};

export function ExecutiveDashboard() {
  const navigate = useNavigate();
  const [stats, setStats] = useState({
    pendingARC: 0, openViolations: 0, delinquentUnits: 0, totalOwners: 0, openRequests: 0,
  });
  const [tasks, setTasks] = useState<any[]>([]);
  const [projects, setProjects] = useState<any[]>([]);
  const [reminders, setReminders] = useState<any[]>([]);
  const [announcements, setAnnouncements] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => { fetchAll(); }, []);

  const fetchAll = async () => {
    try {
      const [arcRes, violRes, unitsRes, ownersRes, reqRes, tasksRes, projectsRes, remindersRes, announcementsRes] = await Promise.all([
        supabase.from("arc_applications").select("id", { count: "exact", head: true }).eq("status", "submitted"),
        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("owners").select("id", { count: "exact", head: true }).eq("status", "active"),
        supabase.from("client_requests").select("id", { count: "exact", head: true }).eq("status", "open"),
        supabase.from("tasks").select("id, title, status, priority, due_date, assigned_to").neq("status", "completed").order("due_date", { ascending: true }).limit(8),
        supabase.from("projects").select("id, title, status, priority, due_date, associations(name)").neq("status", "completed").order("due_date", { ascending: true }).limit(8),
        supabase.from("reminders").select("id, title, due_date, status, description").neq("status", "dismissed").order("due_date", { ascending: true }).limit(8),
        supabase.from("announcements").select("id, title, content, created_at, visibility, pinned").eq("status", "active").order("pinned", { ascending: false }).order("created_at", { ascending: false }).limit(3),
      ]);
      setStats({
        pendingARC: arcRes.count || 0,
        openViolations: violRes.count || 0,
        delinquentUnits: unitsRes.count || 0,
        totalOwners: ownersRes.count || 0,
        openRequests: reqRes.count || 0,
      });
      setTasks(tasksRes.data || []);
      setProjects(projectsRes.data || []);
      setReminders(remindersRes.data || []);
      setAnnouncements(announcementsRes.data || []);
    } catch (err) {
      console.error("Error fetching dashboard data:", err);
    } finally {
      setLoading(false);
    }
  };

  const kpiCards = [
    { title: "Pending ARC", desc: "Needs review", value: stats.pendingARC, icon: FileText, color: "text-primary", bg: "bg-primary/10", path: "/dashboard/arc-applications" },
    { title: "Open Violations", desc: "Active cases", value: stats.openViolations, icon: ShieldAlert, color: "text-destructive", bg: "bg-destructive/10", path: "/dashboard/violations" },
    { title: "Collections", desc: "Delinquent units", value: stats.delinquentUnits, icon: DollarSign, color: "text-warning", bg: "bg-warning/10", path: "/dashboard/collections" },
    { title: "Active Owners", desc: "Total registered", value: stats.totalOwners, icon: Users, color: "text-primary", bg: "bg-primary/5", path: "/dashboard/owner-roster" },
    { title: "Open Requests", desc: "Awaiting response", value: stats.openRequests, icon: MessageCircle, color: "text-purple-600", bg: "bg-purple-500/10", path: "/dashboard/client-requests" },
  ];

  const formatDue = (dateStr: string | null) => {
    if (!dateStr) return null;
    const d = new Date(dateStr);
    if (isToday(d)) return "Today";
    if (isTomorrow(d)) return "Tomorrow";
    if (isPast(d)) return "Overdue";
    return format(d, "MMM d");
  };

  const dueBadge = (dateStr: string | null) => {
    if (!dateStr) return null;
    const d = new Date(dateStr);
    const overdue = isPast(d) && !isToday(d);
    const today = isToday(d);
    return (
      <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-2xs font-medium border ${overdue ? "cc-badge-danger" : today ? "cc-badge-warning" : "cc-badge-neutral"}`}>
        {formatDue(dateStr)}
      </span>
    );
  };

  const container = { hidden: { opacity: 0 }, show: { opacity: 1, transition: { staggerChildren: 0.05 } } };
  const item = { hidden: { opacity: 0, y: 10 }, show: { opacity: 1, y: 0 } };

  // Derived health metrics
  const complianceRate = stats.totalOwners > 0 ? Math.round(((stats.totalOwners - stats.openViolations) / stats.totalOwners) * 100) : 100;
  const delinquencyRate = stats.totalOwners > 0 ? Math.round((stats.delinquentUnits / stats.totalOwners) * 100) : 0;

  return (
    <div className="space-y-5 w-full p-5">
      {/* Hero Banner */}
      <motion.div initial={{ opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className="rounded-xl px-6 py-7 md:px-8 md:py-8 relative overflow-hidden" style={{ background: "linear-gradient(135deg, #0F1E3D 0%, #2563EB 100%)" }}>
        <div className="absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdHRlcm4gaWQ9ImdyaWQiIHdpZHRoPSI2MCIgaGVpZ2h0PSI2MCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHBhdGggZD0iTSA2MCAwIEwgMCAwIDAgNjAiIGZpbGw9Im5vbmUiIHN0cm9rZT0icmdiYSgyNTUsMjU1LDI1NSwwLjA0KSIgc3Ryb2tlLXdpZHRoPSIxIi8+PC9wYXR0ZXJuPjwvZGVmcz48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJ1cmwoI2dyaWQpIi8+PC9zdmc+')] opacity-60" />
        <div className="relative z-10 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
          <div>
            <h1 className="text-[22px] font-semibold text-white tracking-tight">Executive Dashboard</h1>
            <p className="text-white/50 text-[13px] mt-1 max-w-lg">Overview of all association operations, tasks, and compliance metrics.</p>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="secondary" size="sm" className="h-8 text-[12px] bg-white/10 hover:bg-white/20 text-white border-0 backdrop-blur-sm" onClick={() => navigate("/dashboard/reports")}>
              <PieChartIcon className="w-3.5 h-3.5 mr-1.5" /> Reports
            </Button>
            <Button size="sm" className="h-8 text-[12px] bg-white text-foreground hover:bg-white/90 shadow-sm" onClick={() => navigate("/dashboard/arc-applications")}>
              <Plus className="w-3.5 h-3.5 mr-1.5" /> New Action
            </Button>
          </div>
        </div>
      </motion.div>

      {/* KPI Cards */}
      <motion.div variants={container} initial="hidden" animate="show" className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
        {kpiCards.map((card, idx) => (
          <motion.div key={idx} variants={item}>
            <Card className="cc-card-hover cursor-pointer border shadow-sm" onClick={() => navigate(card.path)}>
              <CardContent className="p-3.5">
                <div className="flex items-center justify-between mb-2">
                  <div className={`p-1.5 rounded-lg ${card.bg}`}>
                    <card.icon className={`w-4 h-4 ${card.color}`} />
                  </div>
                  <ArrowUpRight className="w-3.5 h-3.5 text-muted-foreground/30" />
                </div>
                <p className="text-[28px] font-semibold tracking-tight leading-none">{loading ? "—" : card.value}</p>
                <p className="text-[12px] text-foreground mt-1.5 font-medium">{card.title}</p>
                <p className="text-[11px] text-muted-foreground mt-0.5">{card.desc}</p>
              </CardContent>
            </Card>
          </motion.div>
        ))}
      </motion.div>

      {/* Admin Cards Row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <StripeTransactionsCard />
        <AutopayManagementCard />
        <FormInboxCard />
      </div>

      {/* Community Health + Recent Activity */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Community Health */}
        <Card className="border shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4">
            <CardTitle className="text-[15px] font-semibold flex items-center gap-2">
              <Shield className="h-4 w-4 text-primary" /> Community Health
            </CardTitle>
            <CardDescription className="text-[12px]">Key performance indicators across your portfolio</CardDescription>
          </CardHeader>
          <CardContent className="px-4 pb-4">
            <div className="grid grid-cols-2 gap-3">
              <HealthMetric label="Compliance Rate" value={`${complianceRate}%`} icon={<Shield className="w-3.5 h-3.5 text-emerald-600" />} color="bg-emerald-50 text-emerald-700" />
              <HealthMetric label="Delinquency Rate" value={`${delinquencyRate}%`} icon={<TrendingUp className="w-3.5 h-3.5 text-amber-600" />} color="bg-amber-50 text-amber-700" />
              <HealthMetric label="Active Projects" value={String(projects.length)} icon={<Layers className="w-3.5 h-3.5 text-primary" />} color="bg-primary/10 text-primary" />
              <HealthMetric label="Upcoming Deadlines" value={String(reminders.length)} icon={<CalendarClock className="w-3.5 h-3.5 text-purple-600" />} color="bg-purple-50 text-purple-700" />
            </div>
          </CardContent>
        </Card>

        {/* Recent Activity */}
        <Card className="border shadow-sm">
          <CardHeader className="pb-2 px-4 pt-4">
            <CardTitle className="text-[15px] font-semibold flex items-center gap-2">
              <Activity className="h-4 w-4 text-primary" /> Recent Activity
            </CardTitle>
            <CardDescription className="text-[12px]">Latest events across all associations</CardDescription>
          </CardHeader>
          <CardContent className="px-0 pb-0">
            <div className="divide-y divide-border">
              {[
                { text: "ARC Request Submitted", time: "2h ago", icon: <FileText className="w-3.5 h-3.5 text-primary" /> },
                { text: "Violation Notice Sent", time: "Today", icon: <ShieldAlert className="w-3.5 h-3.5 text-destructive" /> },
                { text: "Payment Posted", time: "Today", icon: <DollarSign className="w-3.5 h-3.5 text-emerald-600" /> },
                { text: "New Owner Added", time: "Yesterday", icon: <Users className="w-3.5 h-3.5 text-muted-foreground" /> },
              ].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">{entry.text}</p>
                  </div>
                  <span className="text-[11px] text-muted-foreground shrink-0">{entry.time}</span>
                </div>
              ))}
            </div>
            <Button variant="ghost" className="w-full text-muted-foreground text-[11px] font-semibold h-8 hover:text-primary rounded-t-none border-t border-border">
              View All Activity <ArrowRight className="w-3 h-3 ml-1" />
            </Button>
          </CardContent>
        </Card>
      </div>

      {/* Announcements */}
      {announcements.length > 0 && (
        <Card className="border-primary/15 bg-primary/[0.02] shadow-sm overflow-hidden">
          <div className="flex items-center gap-2 px-4 py-2.5 border-b border-primary/10 bg-primary/5">
            <Megaphone className="w-3.5 h-3.5 text-primary" />
            <span className="text-[13px] font-semibold text-foreground">Announcements</span>
            <Badge variant="secondary" className="text-2xs ml-auto h-5">{announcements.length}</Badge>
            <Button variant="ghost" size="sm" className="text-[11px] text-primary h-6 px-2" onClick={() => navigate("/dashboard/announcements")}>
              View All <ArrowRight className="w-3 h-3 ml-1" />
            </Button>
          </div>
          <div className="divide-y divide-primary/5">
            {announcements.map((ann) => (
              <div key={ann.id} className="px-4 py-2.5 hover:bg-primary/[0.02] transition-colors cursor-pointer" onClick={() => navigate("/dashboard/announcements")}>
                <div className="flex items-center justify-between gap-3">
                  <div className="min-w-0">
                    <p className="text-[13px] font-medium text-foreground truncate">{ann.title}</p>
                    <p className="text-[12px] text-muted-foreground truncate mt-0.5">{htmlToPlainText(ann.content)}</p>
                  </div>
                  <span className="text-2xs text-muted-foreground shrink-0">{format(new Date(ann.created_at), "MMM d")}</span>
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* Ticket Panels */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <TicketPanel
          icon={<CheckSquare className="w-4 h-4 text-primary" />}
          title="Tasks"
          count={tasks.length}
          items={tasks}
          renderItem={(t: any) => (
            <div key={t.id} className="px-4 py-2.5 flex items-center justify-between gap-2 hover:bg-muted/50 transition-colors cursor-pointer" onClick={() => navigate("/dashboard/tasks")}>
              <div className="min-w-0 flex-1">
                <p className="text-[13px] font-medium text-foreground truncate">{t.title}</p>
                <div className="flex items-center gap-1.5 mt-0.5">
                  {t.priority && <span className={`inline-flex items-center rounded-full px-1.5 py-0 text-2xs font-medium border ${priorityColors[t.priority] || "cc-badge-neutral"}`}>{t.priority}</span>}
                  {t.assigned_to && <span className="text-2xs text-muted-foreground truncate">{t.assigned_to}</span>}
                </div>
              </div>
              {dueBadge(t.due_date)}
            </div>
          )}
          viewAllPath="/dashboard/tasks"
          viewAllLabel="View All Tasks"
          navigate={navigate}
        />

        <TicketPanel
          icon={<FolderOpen className="w-4 h-4 text-purple-600" />}
          title="Projects"
          count={projects.length}
          items={projects}
          renderItem={(p: any) => (
            <div key={p.id} className="px-4 py-2.5 flex items-center justify-between gap-2 hover:bg-muted/50 transition-colors cursor-pointer" onClick={() => navigate(`/dashboard/projects/${p.id}`)}>
              <div className="min-w-0 flex-1">
                <p className="text-[13px] font-medium text-foreground truncate">{p.title}</p>
                <div className="flex items-center gap-1.5 mt-0.5">
                  <span className={`inline-flex items-center rounded-full px-1.5 py-0 text-2xs font-medium border ${statusColors[p.status] || "cc-badge-neutral"}`}>{p.status}</span>
                  {p.associations?.name && <span className="text-2xs text-muted-foreground truncate">{p.associations.name}</span>}
                </div>
              </div>
              {dueBadge(p.due_date)}
            </div>
          )}
          viewAllPath="/dashboard/projects"
          viewAllLabel="View All Projects"
          navigate={navigate}
        />

        <TicketPanel
          icon={<Bell className="w-4 h-4 text-warning" />}
          title="Reminders"
          count={reminders.length}
          items={reminders}
          renderItem={(r: any) => (
            <div key={r.id} className="px-4 py-2.5 flex items-center justify-between gap-2 hover:bg-muted/50 transition-colors cursor-pointer" onClick={() => navigate("/dashboard/reminders")}>
              <div className="min-w-0 flex-1">
                <p className="text-[13px] font-medium text-foreground truncate">{r.title}</p>
                {r.description && <p className="text-2xs text-muted-foreground truncate mt-0.5">{r.description}</p>}
              </div>
              {dueBadge(r.due_date)}
            </div>
          )}
          viewAllPath="/dashboard/reminders"
          viewAllLabel="View All Reminders"
          navigate={navigate}
        />
      </div>

      {/* Quick Actions */}
      <Card className="shadow-sm border">
        <CardHeader className="pb-2 px-4 pt-4">
          <CardTitle className="text-[15px] font-semibold flex items-center gap-2">
            <BarChart3 className="h-4 w-4 text-primary" /> Quick Actions
          </CardTitle>
          <CardDescription className="text-[12px]">Common administrative tasks</CardDescription>
        </CardHeader>
        <CardContent className="px-4 pb-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2">
            {[
              { label: "Generate Violation Notice", path: "/dashboard/violations", icon: ShieldAlert },
              { label: "Review ARC Applications", path: "/dashboard/arc-applications", icon: FileText },
              { label: "Add New Homeowner", path: "/dashboard/owner-roster", icon: Users },
              { label: "Run Financial Report", path: "/dashboard/financial-reports", icon: DollarSign },
            ].map((action) => (
              <Button
                key={action.label}
                variant="outline"
                className="justify-start gap-2 h-9 text-[13px] font-normal hover:bg-primary/5 hover:text-primary hover:border-primary/20 transition-all"
                onClick={() => navigate(action.path)}
              >
                <action.icon className="w-3.5 h-3.5" />
                {action.label}
              </Button>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

/* ── Health Metric ────────────────────── */
function HealthMetric({ label, value, icon, color }: { label: string; value: string; icon: React.ReactNode; color: string }) {
  return (
    <div className="flex items-center gap-3 rounded-lg border border-border bg-card p-3">
      <div className={`flex h-8 w-8 items-center justify-center rounded-lg ${color.split(" ")[0]}`}>
        {icon}
      </div>
      <div>
        <p className="text-[18px] font-semibold tracking-tight leading-none">{value}</p>
        <p className="text-[11px] text-muted-foreground mt-0.5">{label}</p>
      </div>
    </div>
  );
}

/* ── Reusable Ticket Panel ────────────────────── */
function TicketPanel({ icon, title, count, items, renderItem, viewAllPath, viewAllLabel, navigate }: {
  icon: React.ReactNode;
  title: string;
  count: number;
  items: any[];
  renderItem: (item: any) => React.ReactNode;
  viewAllPath: string;
  viewAllLabel: string;
  navigate: (path: string) => void;
}) {
  return (
    <Card className="border shadow-sm h-full flex flex-col">
      <CardHeader className="flex flex-row items-center justify-between pb-1 px-4 pt-3.5">
        <div className="flex items-center gap-2">
          {icon}
          <span className="text-[15px] font-semibold">{title}</span>
        </div>
        <Badge variant="secondary" className="text-2xs h-5">{count}</Badge>
      </CardHeader>
      <CardContent className="p-0 flex-1 flex flex-col">
        {items.length === 0 ? (
          <p className="p-4 text-[13px] text-muted-foreground text-center flex-1 flex items-center justify-center">No {title.toLowerCase()}</p>
        ) : (
          <div className="divide-y divide-border max-h-[300px] overflow-y-auto flex-1">
            {items.map(renderItem)}
          </div>
        )}
        <Button variant="ghost" className="w-full text-muted-foreground text-[11px] font-semibold h-8 hover:text-primary rounded-t-none border-t border-border mt-auto" onClick={() => navigate(viewAllPath)}>
          {viewAllLabel} <ArrowRight className="w-3 h-3 ml-1" />
        </Button>
      </CardContent>
    </Card>
  );
}
