import { useState, useEffect, useRef } from "react";
import { useNavigate, useLocation, NavLink } from "react-router-dom";
import {
  FolderKanban, FileText, Users, LayoutDashboard, MessageCircle,
  Menu, ChevronDown, LogOut, User, Receipt, DollarSign,
} from "lucide-react";
import { homeownerFunctionItems } from "@/lib/portalVisibilityConfig";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem,
  DropdownMenuSeparator, DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useBoardAssociations } from "@/contexts/BoardAssociationContext";
import { supabase } from "@/integrations/supabase/client";
import { MessagesIconButton } from "@/components/MessagesIconButton";
import { NotificationBell } from "@/components/NotificationBell";
import { useAuth } from "@/contexts/AuthContext";
import acmIcon from "@/assets/acm-icon.png";
import { boardFunctionItems } from "@/lib/portalVisibilityConfig";
import { usePortalVisibility } from "@/hooks/usePortalVisibility";

interface BoardTopNavProps {
  displayName: string;
  initials: string;
  userEmail?: string;
  onSignOut: () => void;
}

interface MenuItem {
  title: string;
  url: string;
  icon: React.ComponentType<{ className?: string }>;
}

interface MenuColumn {
  heading: string;
  items: MenuItem[];
}

interface MenuSection {
  label: string;
  triggerIcon: React.ComponentType<{ className?: string }>;
  columns: MenuColumn[];
}

const sectionIcons = {
  Operations: FolderKanban,
  Governance: Users,
  Documents: FileText,
  Communication: MessageCircle,
};

function buildBoardMenuSections(visibleKeys: (key: string) => boolean): MenuSection[] {
  const sections = new Map<string, Map<string, MenuItem[]>>();

  boardFunctionItems.filter((item) => visibleKeys(item.key)).forEach((item) => {
    if (!sections.has(item.section)) sections.set(item.section, new Map());
    const groups = sections.get(item.section)!;
    if (!groups.has(item.group)) groups.set(item.group, []);
    groups.get(item.group)!.push({ title: item.title, url: item.url, icon: item.icon });
  });

  return Array.from(sections.entries()).map(([label, groups]) => ({
    label,
    triggerIcon: sectionIcons[label as keyof typeof sectionIcons] || FolderKanban,
    columns: Array.from(groups.entries()).map(([heading, items]) => ({ heading, items })),
  }));
}


/* ── Mega Menu Panel ── */
function MegaMenuPanel({ section, onNavigate }: { section: MenuSection; onNavigate: (url: string) => void }) {
  const location = useLocation();
  return (
    <div className={cn(
      "grid gap-6 p-5",
      section.columns.length === 1 ? "grid-cols-1 min-w-[220px]" :
      section.columns.length === 2 ? "grid-cols-2 min-w-[400px]" :
      "grid-cols-3 min-w-[560px]"
    )}>
      {section.columns.map((col) => (
        <div key={col.heading} className="space-y-1.5">
          <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50 px-2 pb-1">
            {col.heading}
          </div>
          {col.items.map((item) => {
            const isActive = location.pathname.startsWith(item.url);
            return (
              <button
                key={item.url}
                onClick={() => onNavigate(item.url)}
                className={cn(
                  "flex items-center gap-2.5 w-full rounded-md px-2 py-1.5 text-[13px] transition-colors text-left",
                  "hover:bg-accent/60",
                  isActive ? "bg-primary/10 text-primary font-medium" : "text-foreground/80"
                )}
              >
                <item.icon className={cn("h-3.5 w-3.5 shrink-0", isActive ? "text-primary" : "text-muted-foreground/60")} />
                <span className="truncate flex-1">{item.title}</span>
              </button>
            );
          })}
        </div>
      ))}
    </div>
  );
}

/* ── Mobile Nav Drawer ── */
function MobileNavDrawer({ sections, onNavigate, open, onClose }: {
  sections: MenuSection[];
  onNavigate: (url: string) => void;
  open: boolean;
  onClose: () => void;
}) {
  const location = useLocation();
  if (!open) return null;

  return (
    <>
      <div className="fixed inset-0 bg-black/30 z-40" onClick={onClose} />
      <div className="fixed inset-y-0 left-0 w-72 bg-card border-r border-border z-50 overflow-y-auto">
        <div className="p-4 border-b border-border flex items-center justify-between">
          <span className="text-sm font-semibold">Board Menu</span>
          <Button variant="ghost" size="sm" onClick={onClose} className="h-7 w-7 p-0">✕</Button>
        </div>
        <div className="py-2">
          <button
            onClick={() => { onNavigate("/homeowner"); onClose(); }}
            className={cn(
              "flex items-center gap-2.5 w-full px-4 py-2 text-[13px] hover:bg-accent/60",
              location.pathname === "/homeowner" && "bg-primary/10 text-primary font-medium"
            )}
          >
            <LayoutDashboard className="h-4 w-4" /> Dashboard
          </button>
          {sections.map((section) => (
            <div key={section.label} className="mt-2">
              <div className="px-4 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50">
                {section.label}
              </div>
              {section.columns.flatMap((col) => col.items).map((item) => {
                const isActive = location.pathname.startsWith(item.url);
                return (
                  <button
                    key={item.url}
                    onClick={() => { onNavigate(item.url); onClose(); }}
                    className={cn(
                      "flex items-center gap-2.5 w-full px-4 py-1.5 text-[13px] hover:bg-accent/60",
                      isActive ? "bg-primary/10 text-primary font-medium" : "text-foreground/80"
                    )}
                  >
                    <item.icon className={cn("h-3.5 w-3.5 shrink-0", isActive ? "text-primary" : "text-muted-foreground/60")} />
                    <span className="truncate flex-1">{item.title}</span>
                  </button>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

/* ── Association Selector (inline) ── */
function AssociationSelectorInline() {
  const { associations, selectedAssociationId, setSelectedAssociationId } = useBoardAssociations();
  if (associations.length <= 1) return null;
  return (
    <Select value={selectedAssociationId ?? undefined} onValueChange={setSelectedAssociationId}>
      <SelectTrigger className="h-7 w-[180px] text-[12px] bg-muted/50 border-transparent">
        <SelectValue placeholder="Select association" />
      </SelectTrigger>
      <SelectContent>
        {associations.map((a) => (
          <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

/* ── Main Component ── */
export default function BoardTopNav({ displayName, initials, userEmail, onSignOut }: BoardTopNavProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const { user } = useAuth();
  const { selectedAssociationId } = useBoardAssociations();
  const { canSee } = usePortalVisibility("board", selectedAssociationId);
  const visibleBoardMenuSections = buildBoardMenuSections(canSee);
  const { association: homeownerAssociation } = useHomeowner();
  const { canSee: canSeeHomeowner } = usePortalVisibility("homeowner", homeownerAssociation?.id);
  const homeownerNavItems = homeownerFunctionItems.filter((item) => canSeeHomeowner(item.key));
  const [activeMenu, setActiveMenu] = useState<string | null>(null);
  const [mobileNavOpen, setMobileNavOpen] = useState(false);
  const menuTimeoutRef = useRef<ReturnType<typeof setTimeout>>();

  useEffect(() => {
    setActiveMenu(null);
  }, [location.pathname]);

  const handleMenuEnter = (label: string) => {
    if (menuTimeoutRef.current) clearTimeout(menuTimeoutRef.current);
    setActiveMenu(label);
  };

  const handleMenuLeave = () => {
    menuTimeoutRef.current = setTimeout(() => setActiveMenu(null), 150);
  };

  const handleNavigate = (url: string) => {
    setActiveMenu(null);
    navigate(url);
  };

  return (
    <>
      <header className="sticky top-0 z-30 bg-card border-b border-border">
        {/* Top bar */}
        <div className="flex h-12 items-center gap-3 px-4">
          {/* Mobile hamburger */}
          <Button variant="ghost" size="sm" className="h-8 w-8 p-0 lg:hidden" onClick={() => setMobileNavOpen(true)}>
            <Menu className="h-4 w-4" />
          </Button>

          {/* Logo */}
          <button onClick={() => navigate("/homeowner")} className="flex items-center gap-2 shrink-0 hover:opacity-80 transition-opacity">
            <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary overflow-hidden">
              <img src={acmIcon} alt="ACM" className="h-5 w-5 object-contain" />
            </div>
            <span className="text-[13px] font-semibold text-foreground tracking-tight hidden sm:inline">Community Cloud</span>
          </button>

          <Badge variant="secondary" className="text-[10px] font-semibold hidden sm:inline-flex">
            Board Member
          </Badge>

          {/* Association selector */}
          <div className="hidden md:flex ml-2">
            <AssociationSelectorInline />
          </div>

          <div className="flex-1" />

          {/* User */}
          <div className="flex items-center gap-1">
            <MessagesIconButton to="/homeowner/board/messages" />
            <NotificationBell userId={user?.id} />
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="flex items-center gap-2 hover:opacity-80 transition-opacity cursor-pointer outline-none">
                  <Avatar className="h-7 w-7">
                    <AvatarFallback className="bg-primary/10 text-primary text-[11px] font-semibold">{initials}</AvatarFallback>
                  </Avatar>
                  <div className="hidden md:flex flex-col leading-tight text-left">
                    <span className="text-[13px] font-medium truncate max-w-[120px]">{displayName}</span>
                  </div>
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-52">
                <div className="px-3 py-2 border-b border-border mb-1">
                  <p className="text-[13px] font-medium truncate">{displayName}</p>
                  <p className="text-[11px] text-muted-foreground truncate">{userEmail}</p>
                </div>
                <DropdownMenuItem onClick={() => navigate("/homeowner/profile")} className="text-[13px] gap-2">
                  <User className="h-3.5 w-3.5" /> Profile
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => navigate("/homeowner/ledger")} className="text-[13px] gap-2">
                  <Receipt className="h-3.5 w-3.5" /> Account Ledger
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => navigate("/homeowner/payments")} className="text-[13px] gap-2">
                  <DollarSign className="h-3.5 w-3.5" /> Payments
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => navigate("/homeowner/documents")} className="text-[13px] gap-2">
                  <FileText className="h-3.5 w-3.5" /> Homeowner Documents
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={onSignOut} className="text-[13px] gap-2 text-destructive focus:text-destructive">
                  <LogOut className="h-3.5 w-3.5" /> Sign Out
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {/* Homeowner nav strip — same items as the homeowner portal */}
        {homeownerNavItems.length > 0 && (
          <nav className="hidden sm:flex items-center h-9 px-4 gap-0.5 border-t border-border/50 bg-card overflow-x-auto">
            {homeownerNavItems.map((item) => {
              const isActive = item.href === "/homeowner"
                ? location.pathname === "/homeowner"
                : location.pathname === item.href;
              return (
                <NavLink
                  key={item.href}
                  to={item.href}
                  end={item.href === "/homeowner"}
                  className={cn(
                    "whitespace-nowrap px-3 py-1 rounded-md text-[12px] font-medium transition-colors",
                    isActive
                      ? "bg-primary text-primary-foreground"
                      : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
                  )}
                >
                  {item.label}
                </NavLink>
              );
            })}
          </nav>
        )}

        {/* Mega menu nav bar - desktop */}
        <nav className="hidden lg:flex items-center h-9 px-4 gap-0.5 border-t border-border/50 bg-card">
          <button
            onClick={() => navigate("/homeowner")}
            className={cn(
              "flex items-center gap-1.5 px-3 py-1 rounded-md text-[12px] font-medium transition-colors",
              location.pathname === "/homeowner" ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
            )}
          >
            <LayoutDashboard className="h-3.5 w-3.5" /> Dashboard
          </button>

          {visibleBoardMenuSections.map((section) => (
            <div
              key={section.label}
              className="relative"
              onMouseEnter={() => handleMenuEnter(section.label)}
              onMouseLeave={handleMenuLeave}
            >
              <button
                className={cn(
                  "flex items-center gap-1.5 px-3 py-1 rounded-md text-[12px] font-medium transition-colors",
                  activeMenu === section.label
                    ? "bg-accent text-foreground"
                    : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
                )}
              >
                <section.triggerIcon className="h-3.5 w-3.5" />
                {section.label}
                <ChevronDown className={cn("h-3 w-3 transition-transform", activeMenu === section.label && "rotate-180")} />
              </button>

              {activeMenu === section.label && (
                <div
                  className="absolute left-0 top-full pt-1 z-50"
                  onMouseEnter={() => handleMenuEnter(section.label)}
                  onMouseLeave={handleMenuLeave}
                >
                  <div className="bg-popover border border-border rounded-lg shadow-xl">
                    <MegaMenuPanel section={section} onNavigate={handleNavigate} />
                  </div>
                </div>
              )}
            </div>
          ))}
        </nav>
      </header>

      {/* Mobile drawer */}
      <MobileNavDrawer
        sections={visibleBoardMenuSections}
        onNavigate={(url) => navigate(url)}
        open={mobileNavOpen}
        onClose={() => setMobileNavOpen(false)}
      />
    </>
  );
}
