import { useEffect, useState } from "react";
import { Outlet, useNavigate, NavLink, useLocation } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useUserProfile } from "@/hooks/use-user-profile";
import { useAuth } from "@/contexts/AuthContext";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { LogOut, Users, Gavel } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import acmIcon from "@/assets/acm-icon.png";
import BoardTopNav from "@/components/board/BoardTopNav";
import { BoardAssociationProvider } from "@/contexts/BoardAssociationContext";
import { HomeownerProvider, useHomeowner } from "@/contexts/HomeownerContext";
import SupportChatWidget from "@/components/homeowner/SupportChatWidget";
import { MessagesIconButton } from "@/components/MessagesIconButton";
import { NotificationBell } from "@/components/NotificationBell";
import { homeownerFunctionItems } from "@/lib/portalVisibilityConfig";
import { usePortalVisibility } from "@/hooks/usePortalVisibility";

export default function HomeownerLayout() {
  const [userId, setUserId] = useState<string>();
  const [userEmail, setUserEmail] = useState<string>();
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const { profile } = useUserProfile(userId);
  const { isBoardMember, isRvBoatLot, isArcMember } = useAuth();

  useEffect(() => {
    const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => {
      if (!session) { navigate("/auth"); }
      else { setUserId(session.user.id); setUserEmail(session.user.email ?? undefined); }
      setLoading(false);
    });

    supabase.auth.getSession().then(({ data: { session } }) => {
      if (!session) { navigate("/auth"); }
      else { setUserId(session.user.id); setUserEmail(session.user.email ?? undefined); }
      setLoading(false);
    });

    return () => subscription.unsubscribe();
  }, [navigate]);

  const handleSignOut = async () => {
    await supabase.auth.signOut();
    navigate("/");
  };

  const displayName = profile?.full_name || userEmail || "Resident";
  const initials = profile?.full_name
    ? profile.full_name.split(" ").map((n: string) => n[0]).join("").toUpperCase().slice(0, 2)
    : "R";

  if (loading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  return (
    <HomeownerProvider>
      <div className="min-h-screen flex flex-col bg-background">
        {isBoardMember ? (
          <BoardAssociationProvider>
            <BoardTopNav
              displayName={displayName}
              initials={initials}
              userEmail={userEmail}
              onSignOut={handleSignOut}
            />
            <div className="flex flex-1">
              <main className="flex-1 w-full px-4 sm:px-6 lg:px-8 py-5">
                <Outlet />
              </main>
            </div>
          </BoardAssociationProvider>
        ) : (
          <HomeownerPortalShell
            displayName={displayName}
            initials={initials}
            userId={userId}
            isRvBoatLot={isRvBoatLot}
            isArcMember={isArcMember}
            handleSignOut={handleSignOut}
          />
        )}

        <footer className="border-t border-border bg-card py-3">
          <div className="max-w-full mx-auto px-4 sm:px-6 lg:px-8 flex items-center justify-between text-[11px] text-muted-foreground">
            <span>© {new Date().getFullYear()} Community Cloud. All rights reserved.</span>
            <span>Powered by Community Cloud</span>
          </div>
        </footer>
      </div>
      <SupportChatWidget />
    </HomeownerProvider>
  );
}

export function HomeownerPortalShell({ displayName, initials, userId, isRvBoatLot, isArcMember, handleSignOut }: { displayName: string; initials: string; userId?: string; isRvBoatLot: boolean; isArcMember: boolean; handleSignOut: () => void }) {
  const location = useLocation();
  const { association, ownerRecords, associationNames, currentOwner, selectOwner } = useHomeowner();
  const { canSee } = usePortalVisibility(isRvBoatLot ? "rv_boat_lot" : "homeowner", association?.id);
  const navItems = homeownerFunctionItems.filter((item) => canSee(item.key));
  const isArcReviewsActive = location.pathname.startsWith("/arc");

  return (
    <>
      <header className="sticky top-0 z-50 bg-card border-b border-border">
        <div className="max-w-full mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-12">
            <div className="flex items-center gap-2.5">
              <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 tracking-tight text-foreground">Community Cloud</span>
            </div>

            <nav className="hidden sm:flex items-center gap-0.5">
              {navItems.map((item) => {
                const isActive = item.href === "/homeowner" ? location.pathname === "/homeowner" : location.pathname.startsWith(item.href);
                return (
                  <NavLink
                    key={item.href}
                    to={item.href}
                    end={item.href === "/homeowner"}
                    className={`px-3 py-1.5 rounded-md text-[13px] font-medium transition-colors ${
                      isActive ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
                    }`}
                  >
                    {item.label}
                  </NavLink>
                );
              })}
              {isArcMember && (
                <NavLink
                  to="/arc"
                  className={`px-3 py-1.5 rounded-md text-[13px] font-medium transition-colors inline-flex items-center gap-1.5 ${
                    isArcReviewsActive ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
                  }`}
                >
                  <Gavel className="h-3.5 w-3.5" /> ARC Reviews
                </NavLink>
              )}
            </nav>

            <div className="flex items-center gap-1">
              {ownerRecords.length > 1 && currentOwner && (
                <Select value={currentOwner.id} onValueChange={selectOwner}>
                  <SelectTrigger className="h-7 w-[200px] text-[12px]">
                    <SelectValue placeholder="Select property" />
                  </SelectTrigger>
                  <SelectContent>
                    {ownerRecords.map((o) => (
                      <SelectItem key={o.id} value={o.id} className="text-[12px]">
                        {associationNames[o.association_id] || "Property"}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
              <MessagesIconButton to="/homeowner/messages" />
              <NotificationBell userId={userId} />
              <Avatar className="h-7 w-7 ml-1">
                <AvatarFallback className="bg-primary/10 text-primary text-[10px] font-semibold">
                  {initials}
                </AvatarFallback>
              </Avatar>
              <div className="hidden md:flex flex-col leading-tight">
                <span className="text-[12px] font-medium text-foreground truncate max-w-[100px]">{displayName}</span>
              </div>
              <Button variant="ghost" size="sm" onClick={handleSignOut} className="h-7 gap-1.5 px-2 text-[12px] text-muted-foreground hover:text-foreground">
                <LogOut className="h-3.5 w-3.5" />
                <span className="hidden sm:inline">Sign Out</span>
              </Button>
            </div>
          </div>
        </div>
      </header>

      <div className="sm:hidden border-b border-border bg-card overflow-x-auto">
        <div className="flex gap-1 px-4 py-1.5">
          {navItems.map((item) => {
            const isActive = item.href === "/homeowner" ? location.pathname === "/homeowner" : location.pathname.startsWith(item.href);
            return (
              <NavLink
                key={item.href}
                to={item.href}
                end={item.href === "/homeowner"}
                className={`whitespace-nowrap px-2.5 py-1 rounded-md text-[12px] font-medium ${
                  isActive ? "bg-primary text-primary-foreground" : "text-muted-foreground"
                }`}
              >
                {item.label}
              </NavLink>
            );
          })}
          {isArcMember && (
            <NavLink
              to="/arc"
              className={`whitespace-nowrap px-2.5 py-1 rounded-md text-[12px] font-medium inline-flex items-center gap-1 ${
                isArcReviewsActive ? "bg-primary text-primary-foreground" : "text-muted-foreground"
              }`}
            >
              <Gavel className="h-3.5 w-3.5" /> ARC Reviews
            </NavLink>
          )}
        </div>
      </div>

      <div className="flex flex-1">
        <main className="flex-1 w-full px-4 sm:px-6 lg:px-8 py-5">
          <Outlet />
        </main>
      </div>
    </>
  );
}
