"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Boxes,
  ExternalLink,
  LayoutDashboard,
  LogOut,
  Mail,
  Menu,
  Newspaper,
  Package,
  Settings,
  ShoppingBag,
  Tags,
  TicketPercent,
  Users,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { logoutAction } from "@/app/actions/auth";
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";

const sections = [
  {
    label: "Pilotage",
    items: [{ href: "/admin", label: "Vue d'ensemble", icon: LayoutDashboard }],
  },
  {
    label: "Catalogue",
    items: [
      { href: "/admin/products", label: "Produits", icon: Package },
      { href: "/admin/categories", label: "Catégories", icon: Tags },
      { href: "/admin/inventory", label: "Inventaire", icon: Boxes },
    ],
  },
  {
    label: "Ventes",
    items: [
      { href: "/admin/orders", label: "Commandes", icon: ShoppingBag },
      { href: "/admin/customers", label: "Clients", icon: Users },
      { href: "/admin/coupons", label: "Codes promo", icon: TicketPercent },
    ],
  },
  {
    label: "Contenu",
    items: [
      { href: "/admin/content", label: "Journal", icon: Newspaper },
      { href: "/admin/messages", label: "Messages", icon: Mail },
      { href: "/admin/settings", label: "Réglages", icon: Settings },
    ],
  },
];

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

function NavLinks({ onNavigate }: { onNavigate?: () => void }) {
  const pathname = usePathname();
  return (
    <nav className="mt-8 flex-1 space-y-7 overflow-y-auto px-4 pb-6">
      {sections.map((section) => (
        <div key={section.label}>
          <p className="px-3 text-[12px] font-medium uppercase tracking-[0.2em] text-ivory/65">{section.label}</p>
          <div className="mt-2 space-y-0.5">
            {section.items.map((item) => {
              const Icon = item.icon;
              const active = isActive(pathname, item.href);
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={onNavigate}
                  className={cn(
                    "flex items-center gap-3 rounded-sm px-3 py-2.5 text-[14px] transition-colors",
                    active
                      ? "border-l-2 border-gold bg-ivory/15 pl-[10px] font-medium text-ivory"
                      : "text-ivory/80 hover:bg-ivory/10 hover:text-ivory",
                  )}
                >
                  <Icon className={cn("h-[15px] w-[15px]", active ? "text-gold" : "text-ivory/60")} strokeWidth={1.5} />
                  {item.label}
                </Link>
              );
            })}
          </div>
        </div>
      ))}
    </nav>
  );
}

function Brand({ light = true }: { light?: boolean }) {
  return (
    <Link href="/admin" className="block px-7 pt-7">
      <p className={cn("text-[12px] uppercase tracking-[0.3em]", light ? "text-gold" : "text-gold-ink")}>
        Maison
      </p>
      <p className={cn("mt-1 font-serif text-2xl font-light tracking-[0.08em]", light ? "text-ivory" : "text-charcoal")}>
        DAR ZELLIGE
      </p>
    </Link>
  );
}

function UserBlock({
  userName,
  userEmail,
  readOnly,
}: {
  userName: string;
  userEmail: string;
  readOnly?: boolean;
}) {
  return (
    <div className="border-t border-ivory/15 p-4">
      <div className="flex items-center gap-3 px-2">
        <div className="flex h-9 w-9 items-center justify-center rounded-full border border-gold/40 bg-gold/15 font-serif text-sm text-gold">
          {userName.charAt(0).toUpperCase()}
        </div>
        <div className="min-w-0 flex-1">
          <p className="truncate text-[14px] text-ivory/80">{userName}</p>
          <p className="truncate text-[12px] text-ivory/65">{userEmail}</p>
          {readOnly && (
            <p className="mt-1 inline-block border border-gold/35 px-1.5 py-0.5 text-[11px] uppercase tracking-[0.1em] text-gold/80">
              Démo lecture seule
            </p>
          )}
        </div>
      </div>
      <div className="mt-3 flex items-center gap-1">
        <Link
          href="/fr"
          className="flex flex-1 items-center gap-2 rounded-sm px-3 py-2 text-[13px] text-ivory/75 transition-colors hover:bg-ivory/10 hover:text-ivory"
        >
          <ExternalLink className="h-3.5 w-3.5" />
          Voir la boutique
        </Link>
        <form action={logoutAction}>
          <input type="hidden" name="locale" value="fr" />
          <button
            type="submit"
            aria-label="Se déconnecter"
            className="rounded-sm p-2 text-ivory/70 transition-colors hover:bg-ivory/10 hover:text-ivory"
          >
            <LogOut className="h-4 w-4" />
          </button>
        </form>
      </div>
    </div>
  );
}

export function AdminSidebar({
  userName,
  userEmail,
  readOnly = false,
}: {
  userName: string;
  userEmail: string;
  readOnly?: boolean;
}) {
  return (
    <>
      <aside className="fixed inset-y-0 left-0 z-40 hidden w-64 flex-col bg-charcoal lg:flex">
        <Brand />
        <NavLinks />
        <UserBlock userName={userName} userEmail={userEmail} readOnly={readOnly} />
      </aside>

      <header className="sticky top-0 z-40 flex h-14 items-center justify-between border-b border-line bg-cream px-4 lg:hidden">
        <Link href="/admin" className="font-serif text-lg tracking-[0.08em] text-charcoal">
          DAR ZELLIGE
        </Link>
        <Sheet>
          <SheetTrigger className="flex h-9 w-9 items-center justify-center border border-line text-charcoal">
            <Menu className="h-4 w-4" />
            <span className="sr-only">Ouvrir le menu</span>
          </SheetTrigger>
          <SheetContent side="left" className="flex w-72 flex-col bg-charcoal p-0 text-ivory">
            <SheetTitle className="sr-only">Navigation administration</SheetTitle>
            <Brand />
            <NavLinks />
            <UserBlock userName={userName} userEmail={userEmail} readOnly={readOnly} />
          </SheetContent>
        </Sheet>
      </header>
    </>
  );
}
