"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState, type ReactNode } from "react";
import Icon from "@/components/Icon";
import DialogProvider from "@/components/feedback/DialogProvider";
import { authClient } from "@/lib/auth-client";

export type ShellNavItem = {
  href: string;
  label: string;
  icon: string;
  /** Sous-items (ouvre une sous-section dans la sidebar). */
  children?: { href: string; label: string }[];
};

type ShellProps = {
  brand: string;
  variant: "admin" | "client";
  user: { name: string; email: string };
  nav: ShellNavItem[];
  children: ReactNode;
};

export default function Shell({
  brand,
  variant,
  user,
  nav,
  children,
}: ShellProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [mobileOpen, setMobileOpen] = useState(false);

  function isActive(href: string) {
    if (href === pathname) return true;
    return pathname.startsWith(href + "/");
  }

  async function handleSignOut() {
    await authClient.signOut();
    router.push("/login");
    router.refresh();
  }

  return (
    <div className="min-h-screen flex bg-background">
      {/* Sidebar — desktop fixe, mobile en drawer */}
      <aside
        className={`fixed inset-y-0 left-0 z-40 w-72 bg-white border-r border-outline-variant flex flex-col transform transition-transform duration-300 lg:translate-x-0 ${
          mobileOpen ? "translate-x-0" : "-translate-x-full"
        }`}
      >
        <div className="px-8 py-7 border-b border-outline-variant/40 flex items-center justify-between">
          <Link
            href={variant === "admin" ? "/socialexadmin" : "/espace-client"}
            className="font-serif font-bold text-xl tracking-tighter text-primary"
            onClick={() => setMobileOpen(false)}
          >
            {brand}
          </Link>
          <button
            type="button"
            aria-label="Fermer le menu"
            onClick={() => setMobileOpen(false)}
            className="lg:hidden text-on-surface-variant"
          >
            <Icon name="close" />
          </button>
        </div>

        <nav className="flex-1 overflow-y-auto py-6 px-4">
          <ul className="space-y-1">
            {nav.map((item) => {
              const active = isActive(item.href);
              return (
                <li key={item.href}>
                  <Link
                    href={item.href}
                    onClick={() => setMobileOpen(false)}
                    className={`flex items-center gap-3 px-4 py-3 text-sm font-serif tracking-wide uppercase transition-colors ${
                      active
                        ? "bg-primary text-on-primary"
                        : "text-on-surface hover:bg-surface-container-low"
                    }`}
                  >
                    <Icon
                      name={item.icon}
                      className={`!text-lg ${
                        active ? "text-secondary" : "text-on-surface-variant"
                      }`}
                    />
                    {item.label}
                  </Link>
                  {item.children && active && (
                    <ul className="mt-1 mb-2 ml-7 border-l border-outline-variant/40 pl-4 space-y-1">
                      {item.children.map((child) => {
                        const childActive = pathname === child.href;
                        return (
                          <li key={child.href}>
                            <Link
                              href={child.href}
                              onClick={() => setMobileOpen(false)}
                              className={`block px-3 py-2 text-xs uppercase tracking-wider font-serif transition-colors ${
                                childActive
                                  ? "text-secondary"
                                  : "text-on-surface-variant hover:text-primary"
                              }`}
                            >
                              {child.label}
                            </Link>
                          </li>
                        );
                      })}
                    </ul>
                  )}
                </li>
              );
            })}
          </ul>
        </nav>

        <div className="px-8 py-6 border-t border-outline-variant/40 space-y-4">
          <div className="space-y-1">
            <p className="text-sm font-serif text-primary truncate">
              {user.name}
            </p>
            <p className="text-xs text-on-surface-variant truncate">
              {user.email}
            </p>
          </div>
          <button
            type="button"
            onClick={handleSignOut}
            className="flex items-center gap-2 text-xs uppercase tracking-widest font-serif text-on-surface-variant hover:text-primary transition-colors"
          >
            <Icon name="logout" className="!text-base" />
            Se déconnecter
          </button>
        </div>
      </aside>

      {/* Backdrop mobile */}
      {mobileOpen && (
        <div
          aria-hidden
          className="fixed inset-0 z-30 bg-primary/40 lg:hidden"
          onClick={() => setMobileOpen(false)}
        />
      )}

      {/* Main column */}
      <div className="flex-1 lg:pl-72 flex flex-col min-w-0">
        {/* Header mobile */}
        <header className="lg:hidden flex items-center justify-between px-6 py-4 border-b border-outline-variant/40 bg-white">
          <button
            type="button"
            aria-label="Ouvrir le menu"
            onClick={() => setMobileOpen(true)}
            className="text-on-surface"
          >
            <Icon name="menu" />
          </button>
          <span className="font-serif font-bold text-lg tracking-tighter text-primary">
            {brand}
          </span>
          <span className="w-6" /> {/* Spacer */}
        </header>

        <main className="flex-1 px-6 py-10 lg:px-12 lg:py-14">
          <DialogProvider>{children}</DialogProvider>
        </main>
      </div>
    </div>
  );
}
