"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Bell,
  BarChart3,
  ClipboardList,
  ExternalLink,
  LayoutDashboard,
  LogOut,
  Menu,
  Settings,
  ShoppingBag,
  Users,
  Utensils,
  X,
} from "lucide-react";
import { useState } from "react";

type User_role =
  | "ADMIN"
  | "MANAGER"
  | "WAITER"
  | "KITCHEN"
  | "CASHIER"
  | "CUSTOMER";

type AdminUser = {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  role: User_role;
};

type NavigationItem = {
  label: string;
  href: string;
  icon: React.ElementType;
  roles: User_role[];
};

type NavigationSection = {
  title: string;
  items: NavigationItem[];
};

const navigation: NavigationSection[] = [
  {
    title: "Principal",
    items: [
      {
        label: "Tableau de bord",
        href: "/admin/dashboard",
        icon: LayoutDashboard,
        roles: [
          "ADMIN",
          "MANAGER",
          "WAITER",
          "KITCHEN",
          "CASHIER",
        ],
      },
    ],
  },

  {
    title: "Restaurant",
    items: [
      {
        label: "Menu",
        href: "/admin/menu",
        icon: Utensils,
        roles: ["ADMIN", "MANAGER"],
      },

      {
        label: "Galerie",
        href: "/admin/photos",
        icon: Menu,
        roles: ["ADMIN", "MANAGER"],
      },

      {
        label: "Zones de livraison",
        href: "/admin/delivery-zones",
        icon: ClipboardList,
        roles: ["ADMIN", "MANAGER"],
      },

      {
        label: "Moyens de paiement",
        href: "/admin/payment-accounts",
        icon: ShoppingBag,
        roles: ["ADMIN", "MANAGER"],
      },
    ],
  },

  {
    title: "Exploitation",
    items: [
      {
        label: "Tables",
        href: "/admin/tables",
        icon: ClipboardList,
        roles: [
          "ADMIN",
          "MANAGER",
          "WAITER",
        ],
      },

      {
        label: "Commandes",
        href: "/admin/commandes",
        icon: ShoppingBag,
        roles: [
          "ADMIN",
          "MANAGER",
          "WAITER",
          "KITCHEN",
          "CASHIER",
        ],
      },

      {
        label: "Réservations",
        href: "/admin/reservations",
        icon: ClipboardList,
        roles: [
          "ADMIN",
          "MANAGER",
          "WAITER",
        ],
      },

      {
        label: "Clients",
        href: "/admin/clients",
        icon: Users,
        roles: [
          "ADMIN",
          "MANAGER",
        ],
      },
    ],
  },

  {
    title: "Analyse",
    items: [
      {
        label: "Statistiques",
        href: "/admin/statistiques",
        icon: BarChart3,
        roles: [
          "ADMIN",
          "MANAGER",
        ],
      },
    ],
  },

  {
    title: "Système",
    items: [
      {
        label: "Paramètres",
        href: "/admin/parametres",
        icon: Settings,
        roles: ["ADMIN"],
      },
    ],
  },
];

const roleLabels: Record<User_role, string> = {
  ADMIN: "Administrateur",
  MANAGER: "Manager",
  WAITER: "Serveur",
  KITCHEN: "Cuisine",
  CASHIER: "Caissier",
  CUSTOMER: "Client",
};

export default function AdminLayoutClient({
  children,
  user,
}: {
  children: React.ReactNode;
  user: AdminUser;
}) {
  const pathname = usePathname();

  const [mobileOpen, setMobileOpen] =
    useState(false);

  const [loggingOut, setLoggingOut] =
    useState(false);

  function isActive(href: string) {
    if (href === "/admin/dashboard") {
      return pathname === href;
    }

    return pathname.startsWith(href);
  }

  async function handleLogout() {
    try {
      setLoggingOut(true);

      const response = await fetch(
        "/api/auth/logout",
        {
          method: "POST",
        }
      );

      if (!response.ok) {
        throw new Error(
          "Impossible de se déconnecter."
        );
      }

      window.location.href =
        "/admin/login";
    } catch (error) {
      console.error(
        "Erreur déconnexion :",
        error
      );

      setLoggingOut(false);

      alert(
        "Une erreur est survenue lors de la déconnexion."
      );
    }
  }

  const initials =
    `${user.firstName.charAt(0)}${user.lastName.charAt(0)}`
      .toUpperCase();

  const visibleSections =
    navigation
      .map((section) => ({
        ...section,
        items: section.items.filter(
          (item) =>
            item.roles.includes(user.role)
        ),
      }))
      .filter(
        (section) =>
          section.items.length > 0
      );

  return (
    <div className="h-dvh overflow-hidden bg-[#f8f6f1] text-[#2f2a24]">
      <div className="flex h-full min-h-0">

        {/* ================================= */}
        {/* OVERLAY MOBILE                    */}
        {/* ================================= */}

        {mobileOpen && (
          <button
            type="button"
            aria-label="Fermer le menu"
            onClick={() =>
              setMobileOpen(false)
            }
            className="fixed inset-0 z-40 bg-black/40 backdrop-blur-sm lg:hidden"
          />
        )}

        {/* ================================= */}
        {/* SIDEBAR                           */}
        {/* ================================= */}

        <aside
          className={`
            fixed inset-y-0 left-0 z-50
            flex w-72 flex-col
            border-r border-[#e8e1d6]
            bg-white
            shadow-[4px_0_20px_rgba(47,42,36,0.04)]
            transition-transform duration-300
            lg:translate-x-0
            ${
              mobileOpen
                ? "translate-x-0"
                : "-translate-x-full"
            }
          `}
        >

          {/* LOGO */}

          <div className="flex h-20 shrink-0 items-center justify-between border-b border-[#eee8df] px-7">

            <Link
              href="/admin/dashboard"
              onClick={() =>
                setMobileOpen(false)
              }
              className="group"
            >
              <h1 className="font-serif text-2xl font-semibold tracking-wide text-[#2f2a24] transition-colors group-hover:text-[#a68b5b]">
                Happy Hours
              </h1>

              <p className="mt-1 text-[9px] font-semibold uppercase tracking-[0.35em] text-[#b8863b]">
                Administration
              </p>
            </Link>

            <button
              type="button"
              onClick={() =>
                setMobileOpen(false)
              }
              className="flex h-9 w-9 items-center justify-center rounded-full text-gray-500 transition hover:bg-[#f8f6f1] hover:text-[#a68b5b] lg:hidden"
              aria-label="Fermer le menu"
            >
              <X size={20} />
            </button>

          </div>

          {/* NAVIGATION */}

          <nav className="min-h-0 flex-1 overflow-y-auto px-4 py-6">
            {visibleSections.map(
              (section) => (
                <div
                  key={section.title}
                  className="mb-8 last:mb-0"
                >

                  <p className="mb-3 px-3 text-[10px] font-bold uppercase tracking-[0.2em] text-gray-400">
                    {section.title}
                  </p>

                  <div className="space-y-1">

                    {section.items.map(
                      (item) => {
                        const Icon =
                          item.icon;

                        const active =
                          isActive(
                            item.href
                          );

                        return (
                          <Link
                            key={
                              item.href
                            }
                            href={
                              item.href
                            }
                            onClick={() =>
                              setMobileOpen(
                                false
                              )
                            }
                            className={`
                              group relative flex items-center gap-3
                              rounded-xl px-4 py-3
                              text-sm font-medium
                              transition-all duration-200
                              ${
                                active
                                  ? "bg-[#f5efe5] text-[#a68b5b]"
                                  : "text-[#5f5a53] hover:bg-[#f8f6f1] hover:text-[#2f2a24]"
                              }
                            `}
                          >

                            {active && (
                              <span className="absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r-full bg-[#b8863b]" />
                            )}

                            <Icon
                              size={18}
                              strokeWidth={
                                active
                                  ? 2
                                  : 1.8
                              }
                              className={
                                active
                                  ? "text-[#b8863b]"
                                  : "text-gray-400 transition-colors group-hover:text-[#a68b5b]"
                              }
                            />

                            <span>
                              {item.label}
                            </span>

                          </Link>
                        );
                      }
                    )}

                  </div>
                </div>
              )
            )}
          </nav>

          {/* PROFIL SIDEBAR */}

          <div className="shrink-0 border-t border-[#eee8df] bg-white p-4">

            <div className="rounded-2xl border border-[#eee8df] bg-[#f8f6f1] p-4">

              <div className="flex items-center gap-3">

                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[#d8c19a] text-sm font-bold text-white">
                  {initials}
                </div>

                <div className="min-w-0">

                  <p className="truncate text-sm font-semibold text-[#2f2a24]">
                    {user.firstName}{" "}
                    {user.lastName}
                  </p>

                  <p className="mt-1 text-xs text-[#a68b5b]">
                    {roleLabels[user.role]}
                  </p>

                  <p className="mt-1 truncate text-xs text-gray-400">
                    {user.email}
                  </p>

                </div>

              </div>

            </div>

          </div>

        </aside>

        {/* ================================= */}
        {/* ZONE PRINCIPALE                    */}
        {/* ================================= */}

        <div className="flex h-full min-h-0 min-w-0 flex-1 flex-col lg:pl-72">

          {/* ================================= */}
          {/* HEADER FIXE                       */}
          {/* ================================= */}

          <header className="fixed inset-x-0 top-0 z-30 flex h-20 items-center justify-between border-b border-[#e8e1d6] bg-white/95 px-4 shadow-sm backdrop-blur-xl md:px-6 lg:left-72 lg:px-10">

            {/* GAUCHE */}

            <div className="flex items-center gap-4">

              <button
                type="button"
                onClick={() =>
                  setMobileOpen(true)
                }
                className="flex h-10 w-10 items-center justify-center rounded-xl border border-[#e8e1d6] bg-white transition hover:border-[#d8c19a] hover:bg-[#f8f6f1] lg:hidden"
                aria-label="Ouvrir le menu"
              >
                <Menu size={20} />
              </button>

              <div>
                <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-[#a68b5b]">
                  Administration
                </p>

                <h2 className="mt-1 text-base font-semibold text-[#2f2a24] md:text-lg">
                  Espace de gestion
                </h2>
              </div>

            </div>

            {/* DROITE */}

            <div className="flex items-center gap-3 md:gap-4">

              <Link
                href="/"
                target="_blank"
                className="hidden items-center gap-2 rounded-full border border-[#e8e1d6] px-4 py-2 text-xs font-semibold text-[#5f5a53] transition hover:border-[#d8c19a] hover:bg-[#f8f6f1] hover:text-[#a68b5b] md:flex"
              >
                <ExternalLink size={14} />
                Voir le site
              </Link>

              <button
                type="button"
                className="relative flex h-10 w-10 items-center justify-center rounded-full border border-[#e8e1d6] bg-white text-gray-600 transition hover:border-[#d8c19a] hover:bg-[#f8f6f1] hover:text-[#a68b5b]"
                aria-label="Notifications"
              >
                <Bell size={18} />

                <span className="absolute right-0 top-0 h-2.5 w-2.5 rounded-full border-2 border-white bg-[#b8863b]" />
              </button>

              <div className="flex items-center gap-3 border-l border-[#e8e1d6] pl-3 md:pl-4">

                <div className="hidden text-right sm:block">
                  <p className="text-sm font-semibold text-[#2f2a24]">
                    {user.firstName}{" "}
                    {user.lastName}
                  </p>

                  <p className="text-xs text-gray-500">
                    {roleLabels[user.role]}
                  </p>
                </div>

                <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#d8c19a] text-sm font-bold text-white">
                  {initials}
                </div>

                <button
                  type="button"
                  onClick={
                    handleLogout
                  }
                  disabled={
                    loggingOut
                  }
                  className="flex h-10 w-10 items-center justify-center rounded-full text-red-500 transition hover:bg-red-50 disabled:cursor-not-allowed disabled:opacity-50"
                  aria-label="Déconnexion"
                  title="Déconnexion"
                >
                  <LogOut size={17} />
                </button>

              </div>

            </div>

          </header>

          {/* ================================= */}
          {/* SEULE ZONE QUI SCROLLE            */}
          {/* ================================= */}

          <main className="min-h-0 flex-1 overflow-y-auto pt-20">

            <div className="min-h-full p-4 md:p-6 lg:p-10">

              {children}

            </div>

          </main>

        </div>

      </div>
    </div>
  );
}