'use client';


import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
import {
  ActivityIcon,
  AwardIcon,
  BellIcon,
  BuildingIcon,
  ChartIcon,
  ClockIcon,
  DashboardIcon,
  DatabaseIcon,
  DollarIcon,
  ExternalLinkIcon,
  FlagIcon,
  GaugeIcon,
  GlobeIcon,
  HistoryIcon,
  InboxIcon,
  KeyIcon,
  ListChecksIcon,
  LogOutIcon,
  MailIcon,
  MenuIcon,
  MergeIcon,
  SendIcon,
  ShieldCheckIcon,
  StarIcon,
  UploadIcon,
  UserIcon,
  UsersIcon,
  XIcon,
} from './Icons';
import { BrandMark, BrandName } from './BrandMark';

type Item = { label: string; href: string; Icon: typeof UserIcon; count?: string; roles?: string[] };
const ADMIN = ['owner', 'admin'];
const REVIEWERS = ['owner', 'admin', 'verifier'];

/** Items carry the roles the API allows, so nobody is sent to a page that would answer 403 */
const GROUPS: { title: string; items: Item[] }[] = [
  {
    title: 'Overview',
    items: [
      { label: 'Dashboard', href: '/', Icon: DashboardIcon },
      { label: 'Notifications', href: '/notifications', Icon: BellIcon, count: 'notifications' },
      { label: 'Analytics', href: '/analytics', Icon: ChartIcon, roles: ADMIN },
      { label: 'Data quality', href: '/data-quality', Icon: GaugeIcon },
      { label: 'System health', href: '/health', Icon: ActivityIcon },
    ],
  },
  {
    title: 'Directory',
    items: [
      { label: 'Lawyers', href: '/lawyers', Icon: UsersIcon },
      { label: 'Firms', href: '/firms', Icon: BuildingIcon },
      { label: 'Verification queue', href: '/verification', Icon: ShieldCheckIcon, count: 'verification' },
      { label: 'Profile claims', href: '/claims', Icon: UserIcon, count: 'claims', roles: REVIEWERS },
      { label: 'Credential requests', href: '/change-requests', Icon: AwardIcon, count: 'changeRequests', roles: REVIEWERS },
      { label: 'Duplicates', href: '/duplicates', Icon: MergeIcon, count: 'duplicates' },
      { label: 'Reviews', href: '/reviews', Icon: StarIcon, count: 'reviews' },
      { label: 'Corrections', href: '/corrections', Icon: FlagIcon, count: 'corrections' },
    ],
  },
  {
    title: 'Data',
    items: [
      { label: 'Sources', href: '/sources', Icon: DatabaseIcon },
      { label: 'Import', href: '/imports', Icon: UploadIcon },
    ],
  },
  {
    title: 'Ranking & SEO',
    items: [
      { label: 'Rankings', href: '/rankings', Icon: ChartIcon },
      { label: 'SEO eligibility', href: '/seo', Icon: GlobeIcon },
      { label: 'Search Console', href: '/search-console', Icon: GlobeIcon, roles: ADMIN },
    ],
  },
  {
    title: 'Business',
    items: [
      { label: 'Enquiries', href: '/leads', Icon: InboxIcon, roles: ADMIN },
      { label: 'By lawyer', href: '/leads/lawyers', Icon: UsersIcon, roles: ADMIN },
      { label: 'Failed deliveries', href: '/leads/deliveries', Icon: SendIcon, count: 'failedDeliveries', roles: ADMIN },
      { label: 'Lead rules', href: '/lead-rules', Icon: ClockIcon, roles: ADMIN },
      { label: 'Subscriptions & ads', href: '/commerce', Icon: DollarIcon, roles: ADMIN },
    ],
  },
  {
    title: 'Governance',
    items: [
      { label: 'Audit log', href: '/audit', Icon: HistoryIcon, roles: ADMIN },
      { label: 'Users', href: '/users', Icon: ListChecksIcon, roles: ADMIN },
      { label: 'Email', href: '/email', Icon: MailIcon, roles: ADMIN },
      { label: 'My account security', href: '/settings', Icon: KeyIcon },
    ],
  },
];

const isActive = (path: string, href: string) => (href === '/' ? path === '/' : path === href || path.startsWith(`${href}/`));

function Brand() {
  return (
    <Link href="/" className="flex items-center gap-2.5 rounded-md px-2" aria-label="Justice Choice admin — dashboard">
      <BrandMark />
      <BrandName sub="Admin console" />
    </Link>
  );
}

export function Sidebar({
  counts,
  user,
  publicSite,
  logout,
}: {
  counts: Record<string, number>;
  user: { email: string; name: string | null; role: string; mfa: boolean };
  publicSite: string;
  logout: () => Promise<void>;
}) {
  const path = usePathname();
  const [open, setOpen] = useState(false);
  useEffect(() => setOpen(false), [path]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open]);

  const initials = (user.name ?? user.email)
    .split(/[\s@.]+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((p) => p[0]!.toUpperCase())
    .join('');

  const panel = (
    <div className="flex h-full flex-col">
      <div className="flex items-center justify-between px-3 pb-4 pt-4">
        <Brand />
        <button type="button" onClick={() => setOpen(false)} className="btn btn-ghost btn-icon lg:hidden" aria-label="Close menu">
          <XIcon className="h-5 w-5" />
        </button>
      </div>
      <nav aria-label="Admin" className="flex-1 space-y-5 overflow-y-auto px-3 pb-4 text-[13px]">
        {GROUPS.map((g) => {
          const items = g.items.filter((i) => !i.roles || i.roles.includes(user.role));
          if (!items.length) return null;
          return (
            <div key={g.title}>
              <p className="mb-1.5 px-2.5 text-[10.5px] font-bold uppercase tracking-[0.09em] text-muted">{g.title}</p>
              <ul className="space-y-0.5">
                {items.map(({ label, href, Icon, count }) => {
                  const active = isActive(path, href);
                  const n = count ? counts[count] : 0;
                  return (
                    <li key={href}>
                      <Link
                        href={href}
                        aria-current={active ? 'page' : undefined}
                        className={`group relative flex items-center gap-2.5 rounded-lg px-2.5 py-2 font-medium transition-colors ${
                          active ? 'bg-ledger-soft text-ledger' : 'text-ink-2 hover:bg-sunken hover:text-ink active:bg-rule'
                        }`}
                      >
                        {active && <span aria-hidden className="absolute -left-3 top-1.5 bottom-1.5 w-1 rounded-r-full bg-ledger" />}
                        <Icon className={`h-4 w-4 ${active ? 'text-ledger' : 'text-muted group-hover:text-ink'}`} />
                        <span className="flex-1 truncate">{label}</span>
                        {n > 0 && <span className="num min-w-5 rounded-full bg-brass-soft px-1.5 text-center text-[11px] font-bold leading-5 text-brass">{n > 999 ? '999+' : n}</span>}
                      </Link>
                    </li>
                  );
                })}
              </ul>
            </div>
          );
        })}
      </nav>
      <div className="border-t border-rule p-3">
        <div className="flex items-center gap-2.5 rounded-lg px-2 py-1.5">
          <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-gradient-to-br from-ledger-soft to-sunken text-xs font-bold text-ledger">{initials}</span>
          <div className="min-w-0 flex-1 text-xs">
            <p className="truncate font-semibold text-ink">{user.name ?? user.email}</p>
            <p className="truncate text-muted">
              <span className="capitalize">{user.role.replace('_', ' ')}</span> · {user.mfa ? 'MFA' : 'password'} session
            </p>
          </div>
        </div>
        <div className="mt-2 grid grid-cols-2 gap-1.5">
          <a href={publicSite} target="_blank" rel="noopener" className="btn btn-quiet btn-xs">
            <ExternalLinkIcon className="h-3.5 w-3.5" /> Public site
          </a>
          <form action={logout}>
            <button className="btn btn-quiet btn-xs w-full hover:!border-danger hover:!text-danger">
              <LogOutIcon className="h-3.5 w-3.5" /> Sign out
            </button>
          </form>
        </div>
      </div>
    </div>
  );

  return (
    <>
      {/* Mobile top bar */}
      <div className="sticky top-0 z-30 flex items-center justify-between border-b border-rule bg-surface/90 px-3 py-2 backdrop-blur lg:hidden">
        <Brand />
        <button type="button" onClick={() => setOpen(true)} className="btn btn-ghost btn-icon" aria-label="Open menu" aria-expanded={open} aria-controls="admin-sidebar">
          <MenuIcon className="h-5 w-5" />
        </button>
      </div>
      {open && <div className="fixed inset-0 z-40 bg-ink/40 backdrop-blur-[2px] lg:hidden" onClick={() => setOpen(false)} aria-hidden />}
      <aside
        id="admin-sidebar"
        className={`fixed inset-y-0 left-0 z-50 w-[16rem] border-r border-rule bg-surface shadow-lg transition-transform duration-200 lg:sticky lg:top-0 lg:z-auto lg:h-screen lg:translate-x-0 lg:shadow-none ${
          open ? 'translate-x-0' : '-translate-x-full'
        }`}
      >
        {panel}
      </aside>
    </>
  );
}
