import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useUserProfile } from "@/hooks/use-user-profile";
import { useAuth } from "@/contexts/AuthContext";
import { HomeownerProvider } from "@/contexts/HomeownerContext";
import { HomeownerPortalShell } from "./HomeownerLayout";

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

  useEffect(() => {
    const { data: { subscription } } = supabase.auth.onAuthStateChange((_e, 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 || "ARC Member";
  const initials = profile?.full_name
    ? profile.full_name.split(" ").map((n) => n[0]).join("").toUpperCase().slice(0, 2)
    : "A";

  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">
        <HomeownerPortalShell
          displayName={displayName}
          initials={initials}
          userId={userId}
          isRvBoatLot={isRvBoatLot}
          isArcMember={isArcMember}
          handleSignOut={handleSignOut}
        />
      </div>
    </HomeownerProvider>
  );
}