"use client";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { Bell, LogOut, Menu, X, ChevronsUpDown, LayoutDashboard, Package, Receipt, CreditCard, Headphones, ShieldCheck, Users, BarChart3, Boxes, Wallet, Printer, Settings, ScrollText, KeyRound, Store, FileText, Globe } from "lucide-react";
import { Logo } from "../Logo";
import { ago } from "@/lib/format";
import { call } from "../ui";

const NAVI: Record<string, any> = { dash: LayoutDashboard, products: Package, orders: Receipt, payments: CreditCard, support: Headphones, security: ShieldCheck, customers: Users, analytics: BarChart3, catalog: Boxes, gateways: Wallet, printer: Printer, settings: Settings, audit: ScrollText, licenses: KeyRound, store: Store, invoice: FileText, projects: Globe };
export type NavItem = { href: string; label: string; icon: keyof typeof NAVI; badge?: number };

function Bell_() {
  const [open, setOpen] = useState(false); const [d, setD] = useState<any>({ items: [], unread: 0 }); const router = useRouter();
  const load = async () => { const r = await fetch("/api/notifications", { cache: "no-store" }).catch(() => null); if (r?.ok) setD(await r.json()); };
  useEffect(() => { load(); const t = setInterval(load, 20000); return () => clearInterval(t); }, []);
  return (
    <div className="relative">
      <button onClick={() => { setOpen(!open); if (!open) load(); }} className="relative grid h-10 w-10 place-items-center rounded-full border border-slate-200 bg-white hover:bg-slate-50" aria-label="Notifications">
        <Bell size={18} />{d.unread > 0 && <span className="absolute -right-0.5 -top-0.5 grid h-4 min-w-4 place-items-center rounded-full bg-rose-500 px-1 text-[10px] font-bold text-white">{d.unread}</span>}</button>
      {open && <><div className="fixed inset-0 z-30" onClick={() => setOpen(false)} />
        <div className="card absolute right-0 z-40 mt-2 w-[min(22rem,90vw)] overflow-hidden shadow-2xl">
          <div className="flex items-center justify-between border-b border-slate-100 px-4 py-3"><b className="text-sm">Notifications</b><button className="text-xs font-semibold text-brand" onClick={async () => { await call("/api/notifications"); load(); }}>Mark all read</button></div>
          <ul className="max-h-80 divide-y divide-slate-50 overflow-y-auto">
            {d.items.length === 0 && <li className="p-6 text-center text-sm text-slate-400">You’re all caught up</li>}
            {d.items.map((n: any) => <li key={n.id}><button onClick={() => { setOpen(false); if (n.link) router.push(n.link); }} className={`block w-full px-4 py-3 text-left hover:bg-slate-50 ${n.read ? "" : "bg-blue-50/50"}`}><div className="text-sm font-semibold">{n.title}</div>{n.body && <div className="truncate text-xs text-slate-500">{n.body}</div>}<div className="mt-0.5 text-[10px] text-slate-400">{ago(n.created_at)}</div></button></li>)}
          </ul></div></>}
    </div>
  );
}

export function DashShell({ nav, user, area, children, extra }: { nav: { group?: string; items: NavItem[] }[]; user: { name: string; email: string; role: string }; area: "portal" | "admin"; children: React.ReactNode; extra?: React.ReactNode }) {
  const path = usePathname(), router = useRouter(); const [open, setOpen] = useState(false);
  useEffect(() => setOpen(false), [path]);
  const active = (h: string) => (h === `/${area}` ? path === h : path.startsWith(h));
  const side = (
    <div className="flex h-full flex-col">
      <div className="flex h-[72px] items-center px-5"><Logo href={`/${area}`} sub={false} /><span className="ml-2 rounded-md bg-slate-100 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-slate-500">{area === "admin" ? "Console" : "Portal"}</span></div>
      <nav className="flex-1 space-y-5 overflow-y-auto px-3 pb-4" aria-label="Sidebar">
        {nav.map((g, i) => <div key={i}>{g.group && <div className="mb-1.5 px-3 text-[10px] font-bold uppercase tracking-[.14em] text-slate-400">{g.group}</div>}
          <div className="space-y-0.5">{g.items.map((n) => { const I = NAVI[n.icon] || LayoutDashboard; return (
            <Link key={n.href} href={n.href} className="side-link" aria-current={active(n.href) ? "page" : undefined}><I size={18} />{n.label}{!!n.badge && <span className={`ml-auto rounded-full px-1.5 py-0.5 text-[10px] font-bold ${active(n.href) ? "bg-white/25 text-white" : "bg-rose-500 text-white"}`}>{n.badge}</span>}</Link>); })}</div></div>)}
      </nav>
      {extra}
      <div className="border-t border-slate-100 p-3"><div className="flex items-center gap-3 rounded-2xl p-2">
        <span className="grid h-10 w-10 place-items-center rounded-full bg-gradient-to-br from-brand to-accent font-bold text-white">{user.name[0]?.toUpperCase()}</span>
        <div className="min-w-0 flex-1"><div className="truncate text-sm font-semibold">{user.name}</div><div className="truncate text-[11px] capitalize text-slate-400">{user.role}</div></div>
        <button title="Sign out" aria-label="Sign out" onClick={async () => { await call("/api/auth/logout"); router.replace("/login"); router.refresh(); }} className="rounded-full p-2 text-slate-400 hover:bg-rose-50 hover:text-rose-600"><LogOut size={17} /></button></div></div>
    </div>
  );
  return (
    <div className="dash lg:pl-64">
      <aside className="fixed inset-y-0 left-0 z-30 hidden w-64 border-r border-slate-200/70 bg-white lg:block">{side}</aside>
      {open && <div className="fixed inset-0 z-50 lg:hidden"><div className="absolute inset-0 bg-slate-900/40" onClick={() => setOpen(false)} /><aside className="rise absolute inset-y-0 left-0 w-72 bg-white shadow-2xl">{side}</aside></div>}
      <header className="sticky top-0 z-20 flex h-16 items-center gap-3 border-b border-slate-200/60 bg-[#f4f6fb]/85 px-4 backdrop-blur-xl sm:px-6">
        <button className="rounded-full p-2 lg:hidden" onClick={() => setOpen(true)} aria-label="Open menu"><Menu /></button>
        <div className="hidden items-center gap-2 text-sm text-slate-500 sm:flex"><span className="dot-live" />All systems operational</div>
        <div className="ml-auto flex items-center gap-2"><Link href="/" className="btn btn-ghost btn-sm hidden sm:inline-flex">View website</Link><Bell_ /></div>
      </header>
      <main className="mx-auto max-w-[1400px] p-4 sm:p-6">{children}</main>
    </div>
  );
}

export const PageHead = ({ title, sub, children }: { title: string; sub?: string; children?: React.ReactNode }) => (
  <div className="mb-6 flex flex-wrap items-end justify-between gap-3"><div><h1 className="text-2xl font-extrabold tracking-tight sm:text-3xl">{title}</h1>{sub && <p className="mt-0.5 text-sm text-slate-500">{sub}</p>}</div><div className="flex flex-wrap gap-2">{children}</div></div>
);
