"use client";

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 { Ticket, BarChart3 } from "lucide-react";
import DashboardSidebar from "@/components/ui/DashboardSidebar";
import UserDropdown from "@/components/UserDropdown";

const navItems = [
  {
    label: "Dashboard",
    href: "/employe/dashboard",
    icon: <BarChart3 className="w-5 h-5" />,
    color: "green",
  },
  {
    label: "Validation des Tickets",
    href: "/employe/verification",
    icon: <Ticket className="w-5 h-5" />,
    color: "emerald",
  },
];

export default function EmployeLayout({
  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 !== "EMPLOYEE") {
      router.push("/");
      toast.error("Accès refusé : rôle employé 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 !== "EMPLOYEE") {
    return null;
  }

  return (
    <div className="flex min-h-screen bg-gray-50">
      <DashboardSidebar
        navItems={navItems}
        title="Thé Tip Top"
        subtitle="Espace Employé"
      />

      <div className="flex-1 flex flex-col">
        <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="/employe/profil"
              onLogout={handleLogout}
              accentColor="blue"
            />
          </div>
        </header>

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