"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import type { SessionUser } from "@/lib/auth";
import { ROLE_LABEL } from "@/lib/format";

/**
 * Khung điều hướng.
 *
 * Danh sách menu cố tình ngắn — đúng 8 mục nghiệp vụ. Đây là điểm khách hàng
 * chê ở phần mềm cũ ("rườm rà"), nên mỗi lần thêm mục mới phải cân nhắc.
 */
const NAV = [
  // "Hôm nay" là màn hình NVKD mở nhiều nhất khi đi thị trường nên đặt lên đầu;
  // quản lý không đi tuyến nên không thấy mục này.
  { href: "/cong-viec/hom-nay", label: "Hôm nay", icon: "◈", roles: ["SALES"] },
  { href: "/", label: "Tổng quan", icon: "◧", roles: ["DIRECTOR", "GDKV", "MANAGER", "SALES"] },
  { href: "/don-hang", label: "Đơn hàng", icon: "▤", roles: ["DIRECTOR", "GDKV", "MANAGER", "SALES"] },
  { href: "/khach-hang", label: "Khách hàng", icon: "◎", roles: ["DIRECTOR", "GDKV", "MANAGER", "SALES"] },
  { href: "/cong-viec", label: "Công việc", icon: "◔", roles: ["DIRECTOR", "GDKV", "MANAGER", "SALES"] },
  { href: "/bao-cao", label: "Báo cáo", icon: "▦", roles: ["DIRECTOR", "GDKV", "MANAGER", "SALES"] },
  { href: "/phan-tich", label: "Phân tích", icon: "◭", roles: ["DIRECTOR", "GDKV", "MANAGER"] },
  { href: "/canh-bao", label: "Cảnh báo", icon: "◮", roles: ["DIRECTOR", "GDKV", "MANAGER"] },
  { href: "/danh-muc", label: "Danh mục", icon: "☰", roles: ["DIRECTOR", "GDKV", "MANAGER"] },
];

/** Chuông thông báo cá nhân — mở trang /thong-bao. */
function Bell({ count }: { count: number }) {
  return (
    <Link
      href="/thong-bao"
      aria-label={count > 0 ? `Thông báo, ${count} mục mới` : "Thông báo"}
      className="relative inline-flex h-9 w-9 items-center justify-center rounded-lg border border-[var(--color-line)] text-base text-ink-500 hover:bg-ink-50"
    >
      <span aria-hidden>🔔</span>
      {count > 0 && (
        <span className="tnum absolute -right-1.5 -top-1.5 min-w-4 rounded-full bg-red-600 px-1 text-center text-[10px] font-bold leading-4 text-white">
          {count > 99 ? "99+" : count}
        </span>
      )}
    </Link>
  );
}

export function Shell({
  session,
  alertCount,
  notificationCount = 0,
  logoDataUrl,
  children,
  onLogout,
}: {
  session: SessionUser;
  alertCount: number;
  notificationCount?: number;
  logoDataUrl?: string | null;
  children: React.ReactNode;
  onLogout: () => Promise<void>;
}) {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = useState(false);

  // Ngăn kéo mở: khoá cuộn trang phía sau và cho phép đóng bằng phím Esc.
  useEffect(() => {
    if (!mobileOpen) return;
    const previous = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") setMobileOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = previous;
      window.removeEventListener("keydown", onKey);
    };
  }, [mobileOpen]);

  const items = NAV.filter((item) => item.roles.includes(session.role));

  const isActive = (href: string) => {
    if (href === "/") return pathname === "/";
    // "/cong-viec" không được sáng khi đang ở "/cong-viec/hom-nay" — hai mục riêng.
    if (href === "/cong-viec") return pathname === "/cong-viec";
    return pathname.startsWith(href);
  };

  const nav = (
    <nav className="flex flex-col gap-0.5">
      {items.map((item) => (
        <Link
          key={item.href}
          href={item.href}
          onClick={() => setMobileOpen(false)}
          className={`flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors ${
            isActive(item.href)
              ? "bg-ink-100 font-semibold text-brand-600"
              : "text-ink-500 hover:bg-ink-50"
          }`}
        >
          <span aria-hidden className="w-4 text-center text-ink-300">
            {item.icon}
          </span>
          <span className="flex-1">{item.label}</span>
          {item.href === "/canh-bao" && alertCount > 0 && (
            <span className="tnum rounded-full bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-700">
              {alertCount}
            </span>
          )}
        </Link>
      ))}
    </nav>
  );

  return (
    <div className="min-h-dvh lg:flex">
      {/* Thanh trên cùng — chỉ hiện trên điện thoại */}
      <header className="sticky top-0 z-30 flex items-center gap-3 border-b border-[var(--color-line)] bg-white px-4 py-3 lg:hidden">
        <button
          type="button"
          onClick={() => setMobileOpen((open) => !open)}
          className="rounded-lg border border-[var(--color-line)] px-2.5 py-1.5 text-sm"
          aria-expanded={mobileOpen}
          aria-label="Mở menu"
        >
          ☰
        </button>
        <span className="font-bold text-ink-700">CRM</span>
        <span className="ml-auto truncate text-xs text-ink-400">{session.fullName}</span>
        <Bell count={notificationCount} />
      </header>

      {/* Menu điện thoại: ngăn kéo phủ lên trang (overlay) — luôn ở trong màn hình dù đang cuộn ở đâu.
          Danh sách menu cuộn riêng; khối người dùng + Đăng xuất ghim ở đáy ngăn kéo. */}
      {mobileOpen && (
        <div className="fixed inset-0 z-50 lg:hidden" role="dialog" aria-modal="true" aria-label="Menu">
          <button
            type="button"
            aria-label="Đóng menu"
            onClick={() => setMobileOpen(false)}
            className="absolute inset-0 bg-black/40"
          />
          <div className="absolute inset-y-0 left-0 flex w-72 max-w-[85%] flex-col bg-white shadow-xl">
            <div className="flex items-center justify-between border-b border-[var(--color-line)] px-4 py-3">
              <span className="font-bold text-ink-700">CRM</span>
              <button
                type="button"
                onClick={() => setMobileOpen(false)}
                className="rounded-lg border border-[var(--color-line)] px-2.5 py-1 text-sm"
                aria-label="Đóng menu"
              >
                ✕
              </button>
            </div>
            <div className="flex-1 overflow-y-auto px-3 py-3">
              <form action="/tim-kiem" className="mb-2">
                <input
                  type="search"
                  name="q"
                  placeholder="Tìm khách hàng, đơn hàng…"
                  className="input text-sm"
                />
              </form>
              {nav}
            </div>
            <div className="border-t border-[var(--color-line)] px-3 py-3">
              <div className="px-3 pb-2">
                <div className="text-sm font-semibold text-ink-700">{session.fullName}</div>
                <div className="text-[11px] text-ink-400">{ROLE_LABEL[session.role]}</div>
              </div>
              <Link
                href="/tai-khoan"
                onClick={() => setMobileOpen(false)}
                className="btn-ghost mb-1.5 block w-full text-center text-xs"
              >
                Tài khoản của tôi
              </Link>
              <form action={onLogout}>
                <button type="submit" className="btn-ghost w-full text-xs">
                  Đăng xuất
                </button>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Thanh bên — máy tính */}
      <aside className="hidden w-60 shrink-0 border-r border-[var(--color-line)] bg-white lg:sticky lg:top-0 lg:flex lg:h-dvh lg:flex-col">
        <div className="flex items-center gap-2.5 px-5 py-5">
          {logoDataUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={logoDataUrl} alt={session.tenantName} className="h-8 w-8 rounded-lg object-contain" />
          ) : (
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-500 text-sm font-bold text-white">
              C
            </div>
          )}
          <div className="min-w-0 flex-1">
            <div className="truncate text-sm font-bold text-ink-700">CRM Bán hàng</div>
            <div className="truncate text-[11px] text-ink-400">{session.tenantName}</div>
          </div>
          <Bell count={notificationCount} />
        </div>

        <form action="/tim-kiem" className="px-3 pb-3">
          <input
            type="search"
            name="q"
            placeholder="Tìm khách hàng, đơn hàng…"
            className="input text-sm"
          />
        </form>

        <div className="flex-1 overflow-y-auto px-3">{nav}</div>

        <div className="border-t border-[var(--color-line)] p-3">
          <div className="px-2 pb-2">
            <div className="truncate text-sm font-semibold text-ink-700">{session.fullName}</div>
            <div className="text-[11px] text-ink-400">{ROLE_LABEL[session.role]}</div>
          </div>
          <Link href="/tai-khoan" className="btn-ghost mb-1.5 block w-full text-center text-xs">
            Tài khoản của tôi
          </Link>
          <form action={onLogout}>
            <button type="submit" className="btn-ghost w-full text-xs">
              Đăng xuất
            </button>
          </form>
        </div>
      </aside>

      <main className="min-w-0 flex-1 px-4 py-6 lg:px-8 lg:py-8">{children}</main>
    </div>
  );
}
