"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { type ReactNode } from "react";
import {
  IconActivity,
  IconBuilding,
  IconBug,
  IconCreditCard,
  IconDashboard,
  IconFileText,
  IconScroll,
  IconTags,
  IconUsers,
  IconXCircle,
} from "@/components/icons";

type NavItem = { href: string; label: string; icon: ReactNode };

const NAV: NavItem[] = [
  { href: "/dashboard", label: "Tableau de bord", icon: <IconDashboard size={18} /> },
  { href: "/tenants", label: "Tenants", icon: <IconBuilding size={18} /> },
  { href: "/billing", label: "Abonnements", icon: <IconCreditCard size={18} /> },
  { href: "/plans", label: "Plans", icon: <IconTags size={18} /> },
  { href: "/techniciens", label: "Techniciens", icon: <IconUsers size={18} /> },
  { href: "/report-templates", label: "Templates rapports", icon: <IconFileText size={18} /> },
  { href: "/monitoring", label: "Monitoring", icon: <IconActivity size={18} /> },
  { href: "/crashs-mobile", label: "Crashs mobile", icon: <IconBug size={18} /> },
  { href: "/activites", label: "Journal", icon: <IconScroll size={18} /> },
];

// Top bar mobile-only avec hamburger qui ouvre un drawer latéral. Sur md+
// ce composant est entièrement masqué (la sidebar fixe prend le relais).

export function MobileNav({
  userName,
  userEmail,
}: {
  userName: string;
  userEmail: string;
}) {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();

  // Lock scroll quand drawer ouvert
  useEffect(() => {
    if (!open) return;
    const previous = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = previous;
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const initials =
    (userName || userEmail)
      .split(/\s+/)
      .filter(Boolean)
      .slice(0, 2)
      .map((s) => s.charAt(0).toUpperCase())
      .join("") || "?";

  return (
    <>
      <div className="md:hidden flex items-center gap-3 border-b border-border bg-surface px-4 py-3">
        <button
          type="button"
          onClick={() => setOpen(true)}
          aria-label="Ouvrir la navigation"
          className="flex h-9 w-9 items-center justify-center rounded-md border border-border-strong bg-surface hover:bg-surface-2 transition-colors"
        >
          <Hamburger />
        </button>
        <div className="flex items-center gap-2 min-w-0 flex-1">
          <div className="flex h-7 w-7 items-center justify-center rounded-md bg-sidebar text-sidebar-accent ring-1 ring-sidebar-accent/30">
            <span className="text-[11px] font-bold tracking-tighter">mf</span>
          </div>
          <p className="text-sm font-semibold tracking-tight">SuperAdmin</p>
        </div>
      </div>

      {open && (
        <div className="md:hidden fixed inset-0 z-[70] flex mf-fade-in">
          <div
            className="absolute inset-0 bg-foreground/40 backdrop-blur-[2px]"
            onClick={() => setOpen(false)}
          />
          <aside className="relative z-10 flex w-72 max-w-[85vw] flex-col bg-sidebar text-sidebar-foreground shadow-2xl">
            <div className="flex items-center justify-between border-b border-sidebar-active/60 px-5 py-4">
              <div className="flex items-center gap-3">
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-sidebar-accent/15 text-sidebar-accent ring-1 ring-sidebar-accent/30">
                  <span className="text-sm font-bold tracking-tighter">
                    mf
                  </span>
                </div>
                <div>
                  <p className="text-[10px] uppercase tracking-[0.18em] text-sidebar-muted">
                    missioflow
                  </p>
                  <p className="text-sm font-semibold leading-tight">
                    SuperAdmin
                  </p>
                </div>
              </div>
              <button
                type="button"
                onClick={() => setOpen(false)}
                aria-label="Fermer"
                className="text-sidebar-muted hover:text-sidebar-foreground transition-colors"
              >
                <IconXCircle size={18} />
              </button>
            </div>
            <nav className="flex-1 overflow-y-auto px-3 py-4 space-y-0.5">
              {NAV.map((item) => {
                const active =
                  pathname === item.href ||
                  pathname.startsWith(`${item.href}/`);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    aria-current={active ? "page" : undefined}
                    onClick={() => setOpen(false)}
                    className={[
                      "flex items-center gap-3 rounded-md px-3 py-2 text-sm transition-colors",
                      active
                        ? "bg-sidebar-active text-sidebar-foreground"
                        : "text-sidebar-muted hover:bg-sidebar-active/60 hover:text-sidebar-foreground",
                    ].join(" ")}
                  >
                    <span
                      className={
                        active
                          ? "text-sidebar-accent"
                          : "text-sidebar-muted"
                      }
                    >
                      {item.icon}
                    </span>
                    <span>{item.label}</span>
                  </Link>
                );
              })}
            </nav>
            <div className="border-t border-sidebar-active/60 px-4 py-3 flex items-center gap-3">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-sidebar-active text-xs font-semibold text-sidebar-foreground ring-1 ring-sidebar-accent/40">
                {initials}
              </div>
              <div className="min-w-0 flex-1">
                <p className="truncate text-xs font-medium text-sidebar-foreground">
                  {userName || userEmail}
                </p>
                <p className="truncate text-[10px] text-sidebar-muted">
                  {userEmail}
                </p>
              </div>
            </div>
          </aside>
        </div>
      )}
    </>
  );
}

function Hamburger() {
  return (
    <svg
      width={18}
      height={18}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      aria-hidden="true"
    >
      <line x1="4" y1="7" x2="20" y2="7" />
      <line x1="4" y1="12" x2="20" y2="12" />
      <line x1="4" y1="17" x2="20" y2="17" />
    </svg>
  );
}
