import { useEffect, useState } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useUserProfile } from "@/hooks/use-user-profile";
import { useAuth } from "@/contexts/AuthContext";
import { BoardAssociationProvider } from "@/contexts/BoardAssociationContext";
import MasterBoardTopNav from "@/components/master-board/MasterBoardTopNav";

export default function MasterBoardLayout() {
  const [userId, setUserId] = useState<string>();
  const [userEmail, setUserEmail] = useState<string>();
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const { profile } = useUserProfile(userId);
  const { isMasterBoardMember, isStaff, loading: authLoading } = 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]);

  // Role guard: only master board members or staff (admins testing)
  useEffect(() => {
    if (authLoading || !userId) return;
    if (!isMasterBoardMember && !isStaff) {
      navigate("/auth", { replace: true });
    }
  }, [authLoading, userId, isMasterBoardMember, isStaff, navigate]);

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

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

  if (loading || authLoading) {
    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 (
    <BoardAssociationProvider>
      <div className="min-h-screen flex flex-col bg-background">
        <MasterBoardTopNav
          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>
        <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>
    </BoardAssociationProvider>
  );
}
