import { useState, useEffect } from "react";
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 { useAuth } from "@/contexts/AuthContext";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { usePortalVisibility } from "@/hooks/usePortalVisibility";
import { supabase } from "@/integrations/supabase/client";
import { htmlToPlainText } from "@/lib/htmlTextUtils";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  Building2, Home, CreditCard, Receipt, AlertTriangle,
  DollarSign, UserCircle, Clock, Phone, Mail, ArrowRight,
  AlertCircle, FileText, Megaphone, Gavel, BarChart3,
  FileBox, Vote, Calendar, UserCheck, Ticket, Globe
} from "lucide-react";

export default function HomeownerHomePage() {
  const navigate = useNavigate();
  const { isBoardMember, user } = useAuth();
  const { currentOwner, association, unit, ownerRecords, selectOwner, loading } = useHomeowner();
  const { canSee: canSeePortal } = usePortalVisibility("homeowner", association?.id ?? null);

  const [violationCount, setViolationCount] = useState(0);
  const [arcCount, setArcCount] = useState(0);
  const [requestCount, setRequestCount] = useState(0);
  const [announcements, setAnnouncements] = useState<any[]>([]);
  const [pendingBillCount, setPendingBillCount] = useState(0);
  const [openBoardVoteCount, setOpenBoardVoteCount] = useState(0);
  const [upcomingEvents, setUpcomingEvents] = useState<any[]>([]);

  useEffect(() => {
    if (!currentOwner || !association) return;

    // Fetch open violations for this owner's address/association
    const fetchCounts = async () => {
      const [violRes, arcRes, reqRes, annRes, evtRes] = await Promise.all([
        supabase
          .from("violations")
          .select("id", { count: "exact", head: true })
          .eq("association_id", association.id)
          .eq("status", "open")
          .or(`address.eq.${currentOwner.property_address},address.eq.${currentOwner.street_address}`),
        supabase
          .from("arc_applications")
          .select("id", { count: "exact", head: true })
          .eq("association_id", association.id)
          .eq("owner_id", currentOwner.id),
        supabase
          .from("homeowner_requests")
          .select("id", { count: "exact", head: true })
          .eq("association_id", association.id)
          .eq("owner_id", currentOwner.id)
          .neq("status", "closed"),
        supabase
          .from("announcements")
          .select("*")
          .eq("status", "active")
          .order("pinned", { ascending: false })
          .order("created_at", { ascending: false })
          .limit(3),
        supabase
          .from("calendar_events")
          .select("id, title, start_date, end_date, all_day, location, event_type")
          .eq("association_id", association.id)
          .gte("start_date", new Date().toISOString())
          .order("start_date", { ascending: true })
          .limit(5),
      ]);

      setViolationCount(violRes.count ?? 0);
      setArcCount(arcRes.count ?? 0);
      setRequestCount(reqRes.count ?? 0);
      setAnnouncements(annRes.data ?? []);
      setUpcomingEvents(evtRes.data ?? []);
    };

    fetchCounts();
  }, [currentOwner, association]);

  // Fetch pending bill approvals for board members
  useEffect(() => {
    if (!isBoardMember || !user) return;
    const fetchBoardData = async () => {
      // Get board member's association IDs + member IDs
      const { data: bmData } = await supabase
        .from("board_members")
        .select("id, association_id")
        .eq("user_id", user.id);
      if (!bmData?.length) return;
      const assocIds = bmData.map((b: any) => b.association_id);
      const memberIds = bmData.map((b: any) => b.id);

      const [billsRes, votesRes, responsesRes] = await Promise.all([
        supabase
          .from("bills")
          .select("id", { count: "exact", head: true })
          .in("association_id", assocIds)
          .eq("status", "pending"),
        supabase
          .from("board_votes")
          .select("id")
          .in("association_id", assocIds)
          .eq("status", "open"),
        supabase
          .from("board_vote_responses")
          .select("board_vote_id")
          .or(`user_id.eq.${user.id},board_member_id.in.(${memberIds.join(",")})`),
      ]);
      setPendingBillCount(billsRes.count ?? 0);
      const respondedIds = new Set((responsesRes.data ?? []).map((r: any) => r.board_vote_id));
      const open = (votesRes.data ?? []).filter((v: any) => !respondedIds.has(v.id));
      setOpenBoardVoteCount(open.length);
    };
    fetchBoardData();
  }, [isBoardMember, user]);

  if (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 to link your account.</p>
      </div>
    );
  }

  const ownerName = `${currentOwner.first_name} ${currentOwner.last_name}`;
  const balance = currentOwner.balance ?? 0;
  const propertyAddress = unit?.address || currentOwner.property_address || currentOwner.street_address || "—";

  return (
    <div className="space-y-5 w-full">
      {/* Association Selector (if multiple properties) */}
      {ownerRecords.length > 1 && (
        <Select value={currentOwner.id} onValueChange={selectOwner}>
          <SelectTrigger className="w-full max-w-sm">
            <SelectValue placeholder="Select property" />
          </SelectTrigger>
          <SelectContent>
            {ownerRecords.map((o) => (
              <SelectItem key={o.id} value={o.id}>
                {o.first_name} {o.last_name} — {o.property_address || o.street_address || "No address"}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      )}

      {/* Welcome Banner */}
      <Card className="cc-hero-gradient border-0 shadow-card overflow-hidden">
        <CardContent className="p-5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-[18px] font-semibold text-white">Welcome back, {currentOwner.first_name}</h1>
            <div className="flex items-center gap-3 mt-1.5 flex-wrap">
              <span className="flex items-center gap-1.5 text-[12px] text-white/60">
                <Building2 className="h-3.5 w-3.5" /> {association?.name || "—"}
              </span>
              <span className="flex items-center gap-1.5 text-[12px] text-white/60">
                <Home className="h-3.5 w-3.5" /> {propertyAddress}
              </span>
              {unit?.account_number && (
                <span className="text-[12px] text-white/60">
                  #{unit.account_number}
                </span>
              )}
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            {(association as any)?.website && (
              <Button
                asChild
                size="sm"
                variant="outline"
                className="h-8 text-[12px] bg-white/10 text-white border-white/30 hover:bg-white/20 hover:text-white"
              >
                <a
                  href={/^https?:\/\//i.test((association as any).website) ? (association as any).website : `https://${(association as any).website}`}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <Globe className="h-3.5 w-3.5 mr-1.5" /> Association Website
                </a>
              </Button>
            )}
            <Button onClick={() => navigate("/homeowner/payments")} size="sm" className="h-8 text-[12px] bg-white text-foreground hover:bg-white/90 shadow-sm">
              <CreditCard className="h-3.5 w-3.5 mr-1.5" /> Make a Payment
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Community Announcements */}
      <Card className="shadow-card border">
        <CardHeader className="pb-2">
          <div className="flex items-center gap-2">
            <Megaphone className="h-4 w-4 text-primary" />
            <CardTitle className="cc-section-title">Community Announcements</CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          {announcements.length === 0 ? (
            <div className="text-center py-8">
              <Megaphone className="h-6 w-6 text-muted-foreground/20 mx-auto mb-2" />
              <p className="text-[13px] text-muted-foreground">No announcements at this time.</p>
            </div>
          ) : (
            <div className="space-y-3">
              {announcements.map((a) => (
                <div key={a.id} className="p-3 rounded-lg bg-muted/40 border">
                  <p className="text-[13px] font-medium text-foreground">{a.title}</p>
                  <p className="text-[11px] text-muted-foreground mt-1 line-clamp-2">{htmlToPlainText(a.content)}</p>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Board Tools — only for board members (placed under announcements) */}
      {isBoardMember && (
        <Card className="shadow-card border border-primary/15 bg-primary/[0.02]">
          <CardHeader className="pb-2">
            <div className="flex items-center gap-2">
              <BarChart3 className="h-4 w-4 text-primary" />
              <CardTitle className="cc-section-title">Board Tools</CardTitle>
            </div>
            <CardDescription className="text-[12px]">Access board-level administrative features</CardDescription>
          </CardHeader>
          <CardContent>
            {pendingBillCount > 0 && (
              <div
                className="mb-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 flex items-center justify-between cursor-pointer hover:bg-amber-100 dark:hover:bg-amber-950/50 transition-colors"
                onClick={() => navigate("/homeowner/board/bill-approvals")}
              >
                <div className="flex items-center gap-2.5">
                  <UserCheck className="h-4 w-4 text-amber-600 dark:text-amber-400" />
                  <div>
                    <p className="text-[13px] font-semibold text-amber-800 dark:text-amber-300">
                      {pendingBillCount} Bill{pendingBillCount !== 1 ? "s" : ""} Awaiting Approval
                    </p>
                    <p className="text-[11px] text-amber-600 dark:text-amber-400">Click to review and vote</p>
                  </div>
                </div>
                <Badge className="bg-amber-600 text-white text-[11px]">{pendingBillCount}</Badge>
              </div>
            )}
            {openBoardVoteCount > 0 && (
              <div
                className="mb-3 p-3 rounded-lg bg-primary/5 border border-primary/30 flex items-center justify-between cursor-pointer hover:bg-primary/10 transition-colors"
                onClick={() => navigate("/homeowner/board/board-votes")}
              >
                <div className="flex items-center gap-2.5">
                  <Vote className="h-4 w-4 text-primary" />
                  <div>
                    <p className="text-[13px] font-semibold text-primary">
                      {openBoardVoteCount} Board Vote{openBoardVoteCount !== 1 ? "s" : ""} Awaiting Your Response
                    </p>
                    <p className="text-[11px] text-primary/70">Click to cast your vote</p>
                  </div>
                </div>
                <Badge className="bg-primary text-primary-foreground text-[11px]">{openBoardVoteCount}</Badge>
              </div>
            )}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {[
                { icon: BarChart3, label: "Financial Reports", href: "/homeowner/board/financial-reports" },
                { icon: FileBox, label: "Board Documents", href: "/homeowner/board/documents" },
                { icon: Vote, label: "Board Votes", href: "/homeowner/board/board-votes" },
                { icon: Calendar, label: "Meeting Calendar", href: "/homeowner/board/calendar" },
              ].map((tool) => (
                <Button
                  key={tool.label}
                  variant="outline"
                  className="h-auto py-3 flex-col gap-1.5 text-[12px] font-normal hover:bg-primary/5 hover:text-primary hover:border-primary/20"
                  onClick={() => navigate(tool.href)}
                >
                  <tool.icon className="h-4 w-4" />
                  {tool.label}
                </Button>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Summary Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <SummaryCard
          title="Outstanding Balance"
          value={canSeePortal("ledger") ? `$${Math.abs(balance).toFixed(2)}` : "—"}
          icon={<AlertCircle className="h-4 w-4 text-warning" />}
          accent={balance > 0 ? "border-l-warning" : "border-l-success"}
          action={canSeePortal("ledger") ? { label: "View Ledger", onClick: () => navigate("/homeowner/ledger") } : undefined}
        />
        <SummaryCard
          title="Open Violations"
          value={String(violationCount)}
          icon={<AlertTriangle className="h-4 w-4 text-destructive" />}
          accent="border-l-destructive"
        />
        <SummaryCard
          title="ARC Applications"
          value={String(arcCount)}
          icon={<Gavel className="h-4 w-4 text-primary" />}
          accent="border-l-primary"
          action={{ label: "Submit New", onClick: () => navigate("/homeowner/arc") }}
        />
        <SummaryCard
          title="Open Requests"
          value={String(requestCount)}
          icon={<FileText className="h-4 w-4 text-purple-600" />}
          accent="border-l-purple-500"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Quick Actions */}
        <Card className="shadow-card border">
          <CardHeader className="pb-2">
            <CardTitle className="cc-section-title">Quick Actions</CardTitle>
          </CardHeader>
          <CardContent className="space-y-1">
            {[
              { icon: Ticket, label: "Submit Ticket", desc: "Report an issue to staff", href: "/homeowner/tickets" },
              { icon: DollarSign, label: "Make a Payment", desc: "History & payment methods", href: "/homeowner/payments" },
              { icon: Receipt, label: "Account Ledger", desc: "Statements & charges", href: "/homeowner/ledger" },
              { icon: UserCircle, label: "Update Profile", desc: "Contact info & settings", href: "/homeowner/profile" },
              { icon: FileText, label: "My Documents", desc: "View shared documents", href: "/homeowner/documents" },
            ].map((action) => (
              <div
                key={action.label}
                className="flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-muted/60 transition-colors"
                onClick={() => navigate(action.href)}
              >
                <div className="p-2 rounded-lg bg-primary/5">
                  <action.icon className="h-4 w-4 text-primary" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-[13px] font-medium text-foreground">{action.label}</p>
                  <p className="text-[11px] text-muted-foreground">{action.desc}</p>
                </div>
                <ArrowRight className="h-3.5 w-3.5 text-muted-foreground/30" />
              </div>
            ))}
          </CardContent>
        </Card>

        {/* Upcoming Events */}
        <Card className="shadow-card border">
          <CardHeader className="pb-2">
            <div className="flex items-center gap-2">
              <Calendar className="h-4 w-4 text-primary" />
              <CardTitle className="cc-section-title">Upcoming Events</CardTitle>
            </div>
          </CardHeader>
          <CardContent>
            {upcomingEvents.length === 0 ? (
              <div className="flex flex-col items-center justify-center text-center py-10">
                <Calendar className="h-8 w-8 text-muted-foreground/20 mb-2" />
                <p className="text-[13px] font-medium text-muted-foreground">No upcoming events</p>
                <p className="text-[11px] text-muted-foreground mt-0.5">Association events will appear here.</p>
              </div>
            ) : (
              <div className="space-y-2">
                {upcomingEvents.map((evt) => {
                  const start = new Date(evt.start_date);
                  const dateStr = start.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "America/New_York" });
                  const timeStr = evt.all_day ? "All day" : start.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", timeZone: "America/New_York" });
                  return (
                    <div key={evt.id} className="flex items-start gap-3 p-2.5 rounded-lg bg-muted/40 border">
                      <div className="flex-shrink-0 w-12 text-center">
                        <p className="text-[10px] uppercase font-semibold text-primary leading-tight">
                          {start.toLocaleDateString("en-US", { month: "short", timeZone: "America/New_York" })}
                        </p>
                        <p className="text-[18px] font-bold text-foreground leading-tight">
                          {start.toLocaleDateString("en-US", { day: "numeric", timeZone: "America/New_York" })}
                        </p>
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-[13px] font-medium text-foreground truncate">{evt.title}</p>
                        <p className="text-[11px] text-muted-foreground">
                          {dateStr} · {timeStr}
                        </p>
                        {evt.location && (
                          <p className="text-[11px] text-muted-foreground truncate">📍 {evt.location}</p>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </CardContent>
        </Card>
      </div>


      {/* Association Contact */}
      {association && (
        <Card className="shadow-card border bg-navy text-white">
          <CardContent className="p-4">
            <div className="flex items-center gap-2 mb-2.5">
              <Building2 className="h-3.5 w-3.5 text-white/60" />
              <span className="text-[13px] font-semibold">{association.name}</span>
            </div>
            <div className="space-y-1.5 text-[13px] text-white/70">
              {association.phone && (
                <div className="flex items-center gap-2">
                  <Phone className="h-3 w-3" /> {association.phone}
                </div>
              )}
              {association.email && (
                <div className="flex items-center gap-2">
                  <Mail className="h-3 w-3" /> {association.email}
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function SummaryCard({ title, value, icon, accent, action }: {
  title: string;
  value: string;
  icon: React.ReactNode;
  accent: string;
  action?: { label: string; onClick: () => void };
}) {
  return (
    <Card className={`shadow-card border border-l-4 ${accent}`}>
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-2">
          <span className="text-[12px] text-muted-foreground font-medium">{title}</span>
          {icon}
        </div>
        <p className="text-[22px] font-semibold tracking-tight">{value}</p>
        {action && (
          <button onClick={action.onClick} className="text-[12px] font-medium text-primary hover:underline mt-2 flex items-center gap-1">
            {action.label} <ArrowRight className="h-3 w-3" />
          </button>
        )}
      </CardContent>
    </Card>
  );
}
