"use client";

import Sidebar from "@/components/admin/Sidebar";
import { useAuth } from "@/contexts/AuthContext";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { Loading } from "@/components/ui/Loading";
import toast from "react-hot-toast";
import Logo from "@/components/Logo";
import UserDropdown from "@/components/UserDropdown";

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { user, isAuthenticated, isLoading, logout } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push("/login");
      return;
    }

    if (isAuthenticated && user?.role !== "ADMIN") {
      router.push("/");
      toast.error("Accès refusé : rôle administrateur requis");
      return;
    }
  }, [isLoading, isAuthenticated, user, router]);

  const handleLogout = async () => {
    await logout();
    router.push("/login");
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <Loading size="lg" />
      </div>
    );
  }

  if (!isAuthenticated || user?.role !== "ADMIN") {
    return null;
  }

  return (
    <div className="flex min-h-screen bg-gray-50">
      <Sidebar />
      <div className="flex-1 flex flex-col">
        {/* Admin Header */}
        <header className="bg-[#faf8f5] shadow-sm border-b border-gray-200 px-6 py-3">
          <div className="flex items-center justify-end">
            <UserDropdown
              user={user}
              profilePath="/admin/profil"
              onLogout={handleLogout}
              accentColor="red"
            />
          </div>
        </header>

        {/* Main Content */}
        <main className="flex-1 overflow-auto">{children}</main>
      </div>
    </div>
  );
}
