"use client";

import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { AdminSidebar } from "@/components/admin/AdminSidebar";
import { useAuth } from "@/contexts/AuthContext";
import { useLanguage } from "@/contexts/LanguageContext";
import { getToken } from "@/lib/api";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
import LanguageSwitcher from "@/components/LanguageSwitcher";

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const { isAdmin, isLoading } = useAuth();
  const { t } = useLanguage();
  const router = useRouter();
  const pathname = usePathname();
  const isLoginRoute = pathname === "/admin/login";
  const hasToken = typeof window !== "undefined" && !!getToken();

  useEffect(() => {
    if (!isLoading && !isAdmin && !isLoginRoute) {
      router.push("/admin/login");
    }
  }, [isAdmin, isLoading, isLoginRoute, router]);

  if (isLoginRoute) {
    return (
      <div className="min-h-screen flex w-full bg-muted/30">
        <div className="flex-1 flex flex-col">
          <main className="flex-1 p-6">{children}</main>
        </div>
      </div>
    );
  }

  // Still loading auth state, or token exists but isAdmin not yet committed (post-login race)
  if (isLoading || (!isAdmin && hasToken)) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/30">
        <div className="text-sm text-muted-foreground">{t("admin.loading")}</div>
      </div>
    );
  }

  if (!isAdmin) {
    return null;
  }

  // Layout pour l'admin connecté (avec la sidebar)
  return (
    <SidebarProvider>
      <div className="min-h-screen flex w-full bg-muted/30">
        <AdminSidebar />
        <div className="flex-1 flex flex-col">
          <header className="h-14 flex items-center justify-between border-b border-border bg-background px-4 sticky top-0 z-10">
            <div className="flex items-center">
              <SidebarTrigger />
              <h1 className="ml-4 text-sm font-medium text-muted-foreground">
                {t("admin.header")}
              </h1>
            </div>
            <LanguageSwitcher />
          </header>
          <main className="flex-1 p-6">{children}</main>
        </div>
      </div>
    </SidebarProvider>
  );
}