import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Building2, Users, FileText, AlertTriangle, Megaphone, Pin,
  CheckSquare, MessageCircle, DollarSign, ArrowRight, CalendarClock,
} from "lucide-react";
import { useBoardAssociations } from "@/contexts/BoardAssociationContext";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { useUnreadMessages } from "@/hooks/useUnreadMessages";
import { formatDateTimeShortEST } from "@/lib/timezoneUtils";
import { htmlToPlainText } from "@/lib/htmlTextUtils";

export default function MasterBoardDashboardPage() {
  const { associations, associationIds, selectedAssociationId, loading } = useBoardAssociations();
  const { user } = useAuth();
  const { unreadCount } = useUnreadMessages();
  const [stats, setStats] = useState({ owners: 0, openViolations: 0, documents: 0 });
  const [announcements, setAnnouncements] = useState<any[]>([]);
  const [pendingBillCount, setPendingBillCount] = useState(0);
  const [financialSummary, setFinancialSummary] = useState<{ bankBalance: number; openBills: number } | null>(null);
  const [upcomingEvents, setUpcomingEvents] = useState<any[]>([]);

  useEffect(() => {
    if (!selectedAssociationId) return;
    (async () => {
      const [o, v, d] = await Promise.all([
        supabase.from("owners").select("id", { count: "exact", head: true }).eq("association_id", selectedAssociationId).eq("status", "active"),
        supabase.from("violations").select("id", { count: "exact", head: true }).eq("association_id", selectedAssociationId).neq("status", "closed"),
        supabase.from("documents").select("id", { count: "exact", head: true }).eq("association_id", selectedAssociationId),
      ]);
      setStats({ owners: o.count ?? 0, openViolations: v.count ?? 0, documents: d.count ?? 0 });
    })();
  }, [selectedAssociationId]);

  // Announcements (across all assigned associations)
  useEffect(() => {
    if (!associationIds.length) { setAnnouncements([]); return; }
    const nowIso = new Date().toISOString();
    supabase
      .from("announcements")
      .select("id, title, content, created_at, pinned, expires_at, association_id")
      .in("association_id", associationIds)
      .eq("status", "active")
      .or(`expires_at.is.null,expires_at.gt.${nowIso}`)
      .order("pinned", { ascending: false })
      .order("created_at", { ascending: false })
      .limit(5)
      .then(({ data }) => setAnnouncements(data || []));
  }, [associationIds]);

  // Pending bill approvals count for current user across assigned assocs
  useEffect(() => {
    if (!user || !associationIds.length) { setPendingBillCount(0); return; }
    (async () => {
      const billsQ: any = supabase
        .from("bills")
        .select("id")
        .in("association_id", associationIds)
        .in("status", ["pending", "pending_approval", "submitted"]);
      const { data: bills } = await billsQ;
      const billIds = (bills || []).map((b: any) => b.id);
      if (!billIds.length) { setPendingBillCount(0); return; }
      const client: any = supabase;
      const q = client
        .from("bill_approvals")
        .select("id", { count: "exact", head: true })
        .in("bill_id", billIds)
        .eq("approver_user_id", user.id)
        .eq("status", "pending");
      const { count } = await q;
      setPendingBillCount(count ?? 0);
    })();
  }, [user, associationIds]);

  // Financial overview snapshot for selected association
  useEffect(() => {
    if (!selectedAssociationId) { setFinancialSummary(null); return; }
    (async () => {
      const [bankRes, billsRes] = await Promise.all([
        supabase.from("bank_accounts").select("balance").eq("association_id", selectedAssociationId),
        supabase.from("bills").select("amount").eq("association_id", selectedAssociationId).in("status", ["pending", "pending_approval", "approved", "submitted"]),
      ]);
      const bankBalance = (bankRes.data || []).reduce((s, r: any) => s + Number(r.balance || 0), 0);
      const openBills = (billsRes.data || []).reduce((s, r: any) => s + Number(r.amount || 0), 0);
      setFinancialSummary({ bankBalance, openBills });
    })();
  }, [selectedAssociationId]);

  // Upcoming calendar events across assigned associations (next 30 days)
  useEffect(() => {
    if (!associationIds.length) { setUpcomingEvents([]); return; }
    const nowIso = new Date().toISOString();
    const inThirtyIso = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
    supabase
      .from("calendar_events")
      .select("id, title, start_date, end_date, all_day, event_type, location, association_id")
      .in("association_id", associationIds)
      .eq("is_blocked", false)
      .gte("start_date", nowIso)
      .lte("start_date", inThirtyIso)
      .order("start_date", { ascending: true })
      .limit(6)
      .then(({ data }) => setUpcomingEvents(data || []));
  }, [associationIds]);

  const current = associations.find((a) => a.id === selectedAssociationId);
  const assocNameById = (id: string) => associations.find((a) => a.id === id)?.name;

  const fmt = (n: number) =>
    n.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Master Board Dashboard</h1>
        <p className="text-sm text-muted-foreground">
          {loading ? "Loading associations..." : current ? `Viewing: ${current.name}` : "Select an association above to begin."}
        </p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Assigned Associations</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent><div className="text-2xl font-bold">{associations.length}</div></CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Active Owners</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent><div className="text-2xl font-bold">{stats.owners}</div></CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Open Violations</CardTitle>
            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent><div className="text-2xl font-bold">{stats.openViolations}</div></CardContent>
        </Card>
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">Documents</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent><div className="text-2xl font-bold">{stats.documents}</div></CardContent>
        </Card>
      </div>

      {/* Feature cards: Announcements, Bill Approvals, Messages, Financial Overview */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Announcements */}
        <Card className="flex flex-col">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <Megaphone className="h-4 w-4 text-primary" /> Announcements
            </CardTitle>
            <Badge variant="secondary" className="text-2xs h-5">{announcements.length}</Badge>
          </CardHeader>
          <CardContent className="flex-1 p-0">
            {announcements.length === 0 ? (
              <p className="px-6 py-4 text-sm text-muted-foreground">No active announcements.</p>
            ) : (
              <ul className="divide-y divide-border">
                {announcements.map((a) => (
                  <li key={a.id} className="px-6 py-2.5">
                    <div className="flex items-center gap-1.5">
                      {a.pinned && <Pin className="w-3 h-3 text-primary fill-primary shrink-0" />}
                      <p className="text-[13px] font-medium truncate">{a.title}</p>
                    </div>
                    <div className="flex items-center justify-between mt-0.5 gap-2">
                      <p className="text-2xs text-muted-foreground truncate flex-1">
                        {assocNameById(a.association_id)} · {htmlToPlainText(a.content)}
                      </p>
                      <span className="text-2xs text-muted-foreground shrink-0">{formatDateTimeShortEST(a.created_at)}</span>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
          <div className="border-t">
            <Button asChild variant="ghost" className="w-full text-[12px] h-9 rounded-t-none">
              <Link to="/master-board/announcements">View all <ArrowRight className="h-3 w-3 ml-1" /></Link>
            </Button>
          </div>
        </Card>

        {/* Bill Approvals */}
        <Card className="flex flex-col">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <CheckSquare className="h-4 w-4 text-primary" /> Bill Approvals
            </CardTitle>
            <Badge variant={pendingBillCount > 0 ? "default" : "secondary"} className="text-2xs h-5">
              {pendingBillCount} pending
            </Badge>
          </CardHeader>
          <CardContent className="flex-1">
            <p className="text-sm text-muted-foreground">
              {pendingBillCount === 0
                ? "You're all caught up — no bills awaiting your approval."
                : `You have ${pendingBillCount} bill${pendingBillCount === 1 ? "" : "s"} waiting for your review.`}
            </p>
          </CardContent>
          <div className="border-t">
            <Button asChild variant="ghost" className="w-full text-[12px] h-9 rounded-t-none">
              <Link to="/master-board/bill-approvals">Review bills <ArrowRight className="h-3 w-3 ml-1" /></Link>
            </Button>
          </div>
        </Card>

        {/* Messages Inbox */}
        <Card className="flex flex-col">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <MessageCircle className="h-4 w-4 text-primary" /> Messages Inbox
            </CardTitle>
            <Badge variant={unreadCount > 0 ? "default" : "secondary"} className="text-2xs h-5">
              {unreadCount} unread
            </Badge>
          </CardHeader>
          <CardContent className="flex-1">
            <p className="text-sm text-muted-foreground">
              {unreadCount === 0
                ? "No new messages."
                : `${unreadCount} unread message${unreadCount === 1 ? "" : "s"} from staff or fellow board members.`}
            </p>
          </CardContent>
          <div className="border-t">
            <Button asChild variant="ghost" className="w-full text-[12px] h-9 rounded-t-none">
              <Link to="/master-board/messages">Open inbox <ArrowRight className="h-3 w-3 ml-1" /></Link>
            </Button>
          </div>
        </Card>

        {/* Financial Overview */}
        <Card className="flex flex-col">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <DollarSign className="h-4 w-4 text-primary" /> Financial Overview
            </CardTitle>
          </CardHeader>
          <CardContent className="flex-1 space-y-2">
            {!selectedAssociationId ? (
              <p className="text-sm text-muted-foreground">Select an association to view financial highlights.</p>
            ) : !financialSummary ? (
              <p className="text-sm text-muted-foreground">Loading…</p>
            ) : (
              <>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Total Bank Balance</span>
                  <span className="text-base font-semibold">{fmt(financialSummary.bankBalance)}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-muted-foreground">Open Bills</span>
                  <span className="text-base font-semibold">{fmt(financialSummary.openBills)}</span>
                </div>
              </>
            )}
          </CardContent>
          <div className="border-t">
            <Button asChild variant="ghost" className="w-full text-[12px] h-9 rounded-t-none">
              <Link to="/master-board/financial-overview">View full overview <ArrowRight className="h-3 w-3 ml-1" /></Link>
            </Button>
          </div>
        </Card>
      </div>

      <Card>
        <CardHeader><CardTitle className="text-base">Your Associations</CardTitle></CardHeader>
        <CardContent>
          {associations.length === 0 ? (
            <p className="text-sm text-muted-foreground">No associations have been assigned to you yet. Contact your administrator.</p>
          ) : (
            <ul className="space-y-1 text-sm">
              {associations.map((a) => (
                <li key={a.id} className="flex items-center gap-2">
                  <Building2 className="h-3.5 w-3.5 text-muted-foreground" />
                  {a.name}
                </li>
              ))}
            </ul>
          )}
        </CardContent>
        </Card>

        {/* Upcoming Dates */}
        <Card className="flex flex-col lg:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-semibold flex items-center gap-2">
              <CalendarClock className="h-4 w-4 text-primary" /> Upcoming Dates
            </CardTitle>
            <Badge variant="secondary" className="text-2xs h-5">{upcomingEvents.length}</Badge>
          </CardHeader>
          <CardContent className="flex-1 p-0">
            {upcomingEvents.length === 0 ? (
              <p className="px-6 py-4 text-sm text-muted-foreground">No events scheduled in the next 30 days.</p>
            ) : (
              <ul className="divide-y divide-border">
                {upcomingEvents.map((e) => (
                  <li key={e.id} className="px-6 py-2.5 flex items-start gap-3">
                    <div className="text-2xs text-muted-foreground shrink-0 w-28">
                      {e.all_day
                        ? new Date(e.start_date).toLocaleDateString("en-US", { timeZone: "America/New_York", month: "short", day: "numeric" })
                        : formatDateTimeShortEST(e.start_date)}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="text-[13px] font-medium truncate">{e.title}</p>
                      <p className="text-2xs text-muted-foreground truncate">
                        {assocNameById(e.association_id)}
                        {e.location ? ` · ${e.location}` : ""}
                        {e.event_type ? ` · ${e.event_type}` : ""}
                      </p>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
          <div className="border-t">
            <Button asChild variant="ghost" className="w-full text-[12px] h-9 rounded-t-none">
              <Link to="/master-board/calendar">Open calendar <ArrowRight className="h-3 w-3 ml-1" /></Link>
            </Button>
          </div>
        </Card>
      </div>
  );
}
