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 { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { LogOut, Scale } from "lucide-react";

const navItems = [
  { label: "Cases", href: "/legal" },
];

export default function LegalLayout() {
  const [userId, setUserId] = useState<string>();
  const [userEmail, setUserEmail] = useState<string>();
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();
  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: only legal users
  useEffect(() => {
    if (rolesLoading || !userId || roles.length === 0) return;
    const hasLegalAccess = roles.includes("legal" as any);
    const hasStaffAccess = roles.some((r) => ["admin", "manager"].includes(r));
    if (!hasLegalAccess && !hasStaffAccess) {
      navigate("/auth", { replace: true });
    }
  }, [roles, rolesLoading, userId, navigate]);

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

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

  if (loading || rolesLoading) {
    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 (
    <div className="min-h-screen flex flex-col bg-background">
      <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">
                <Scale className="h-4 w-4 text-primary-foreground" />
              </div>
              <span className="text-[13px] font-semibold tracking-tight text-foreground">Legal Portal</span>
            </div>

            <nav className="hidden sm:flex items-center gap-0.5">
              {navItems.map((item) => {
                const isActive = item.href === "/legal"
                  ? location.pathname === "/legal" || location.pathname.startsWith("/legal/case")
                  : location.pathname.startsWith(item.href);
                return (
                  <NavLink
                    key={item.href}
                    to={item.href}
                    end={item.href === "/legal"}
                    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>
                );
              })}
            </nav>

            <div className="flex items-center gap-2">
              <Avatar className="h-7 w-7">
                <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-[120px]">{displayName}</span>
              </div>
              <Button variant="ghost" size="icon" onClick={handleSignOut} className="h-7 w-7 text-muted-foreground hover:text-foreground">
                <LogOut className="h-3.5 w-3.5" />
              </Button>
            </div>
          </div>
        </div>
      </header>

      <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>Legal Portal</span>
        </div>
      </footer>
    </div>
  );
}
