import { useEffect, useState } from "react";
import { Outlet, useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { DashboardTopNav } from "@/components/dashboard/DashboardTopNav";
import { useUserProfile } from "@/hooks/use-user-profile";
import { TickerProvider } from "@/contexts/TickerContext";

const STAFF_ROLES = ["admin", "manager", "employee", "staff"];

export default function DashboardLayout() {
  const [userId, setUserId] = useState<string>();
  const [userEmail, setUserEmail] = useState<string>();
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const { profile, roles, loading: rolesLoading } = useUserProfile(userId);

  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: redirect non-staff users away from admin dashboard
  useEffect(() => {
    if (rolesLoading || !userId || roles.length === 0) return;
    const hasStaffAccess = roles.some((r) => STAFF_ROLES.includes(r));
    if (!hasStaffAccess) {
      navigate("/homeowner", { replace: true });
    }
  }, [roles, rolesLoading, userId, navigate]);

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

  return (
    <TickerProvider>
      <div className="min-h-screen flex flex-col w-full">
        <DashboardTopNav
          userEmail={userEmail}
          fullName={profile?.full_name ?? undefined}
          roles={roles}
          userId={userId}
        />
        <main className="flex-1 min-w-0 overflow-auto bg-secondary/40 p-6">
          <Outlet />
        </main>
      </div>
    </TickerProvider>
  );
}
