'use client';

import { motion, useReducedMotion } from 'framer-motion';
import {
  ArrowDownToLine,
  BookUser,
  Building2,
  ChevronLeft,
  LayoutDashboard,
  LayoutGrid,
  LifeBuoy,
  MoreHorizontal,
  Package,
  Percent,
  Plus,
  ScrollText,
  Settings,
  Truck,
  Users,
  Wallet,
  Webhook,
  type LucideIcon,
} from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useEffect, useId } from 'react';

import { Logo } from '@/components/layout/logo';
import { UserMenu } from '@/components/layout/user-menu';
import { Avatar } from '@/components/ui/avatar';
import { buttonVariants } from '@/components/ui/button';
import { Tooltip } from '@/components/ui/tooltip';
import { ADMIN_NAV } from '@/lib/admin-nav';
import { useAuth } from '@/lib/auth';
import { visibleNav } from '@/lib/nav';
import { publicEnv } from '@/lib/public-env';
import { cn } from '@/lib/utils';
import type { Permission } from '@/shared/permissions';

interface NavEntry {
  href: string;
  label: string;
  icon: LucideIcon;
}

interface NavGroup {
  label: string;
  items: NavEntry[];
}

const appIcons: Record<string, LucideIcon> = {
  '/dashboard': LayoutDashboard,
  '/shipments': Package,
  '/addresses': BookUser,
  '/wallet': Wallet,
  '/settings/team': Users,
  '/settings/profile': Settings,
};

const appGroups: ReadonlyArray<{ label: string; hrefs: readonly string[] }> = [
  { label: 'Main', hrefs: ['/dashboard', '/shipments', '/addresses'] },
  { label: 'Billing', hrefs: ['/wallet'] },
  { label: 'Workspace', hrefs: ['/settings/team', '/settings/profile'] },
];

const adminIcons: Record<string, LucideIcon> = {
  '/admin': LayoutGrid,
  '/admin/tenants': Building2,
  '/admin/topups': ArrowDownToLine,
  '/admin/pricing': Percent,
  '/admin/couriers': Truck,
  '/admin/webhooks': Webhook,
  '/admin/audit': ScrollText,
  '/admin/settings': Settings,
};

const adminGroups: ReadonlyArray<{ label: string; hrefs: readonly string[] }> = [
  { label: 'Platform', hrefs: ['/admin', '/admin/tenants', '/admin/topups'] },
  { label: 'Configuration', hrefs: ['/admin/pricing', '/admin/couriers', '/admin/webhooks'] },
  { label: 'System', hrefs: ['/admin/audit', '/admin/settings'] },
];

const isActive = (href: string, pathname: string): boolean => {
  if (href === '/admin') return pathname === '/admin';
  if (href === '/shipments') return pathname === '/shipments' || (pathname.startsWith('/shipments/') && pathname !== '/shipments/new');
  return pathname === href || pathname.startsWith(`${href}/`);
};

const roleLabel = (role: string): string => role.charAt(0).toUpperCase() + role.slice(1).toLowerCase();

const isTypingTarget = (target: EventTarget | null): boolean =>
  target instanceof HTMLElement && (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));

export function Sidebar({
  variant = 'app',
  permissions = [],
  tenantName,
  pathname,
  collapsed = false,
  onToggleCollapsed,
  onNavigate,
  badges = {},
}: {
  variant?: 'app' | 'admin';
  permissions?: readonly Permission[];
  tenantName: string;
  pathname: string;
  collapsed?: boolean;
  /** Present only on the desktop sidebar. */
  onToggleCollapsed?: () => void;
  onNavigate?: () => void;
  /** Optional count badges keyed by href. */
  badges?: Record<string, number>;
}) {
  const { user } = useAuth();
  const router = useRouter();
  const reduce = useReducedMotion();
  const indicatorId = useId();

  const visible = variant === 'app' ? visibleNav(permissions) : [];
  const canCreate = variant === 'app' && visible.some((item) => item.href === '/shipments/new');
  const groups: NavGroup[] =
    variant === 'app'
      ? appGroups
          .map((group) => ({
            label: group.label,
            items: visible
              .filter((item) => group.hrefs.includes(item.href))
              .map((item) => ({ href: item.href, label: item.label, icon: appIcons[item.href] ?? Package })),
          }))
          .filter((group) => group.items.length > 0)
      : adminGroups.map((group) => ({
          label: group.label,
          items: ADMIN_NAV.filter((item) => group.hrefs.includes(item.href)).map((item) => ({
            href: item.href,
            label: item.label,
            icon: adminIcons[item.href] ?? LayoutGrid,
          })),
        }));

  // Keyboard shortcut "C" opens the create-shipment wizard (desktop sidebar only).
  useEffect(() => {
    if (!canCreate || onToggleCollapsed === undefined) return undefined;
    const onKey = (event: KeyboardEvent) => {
      if (event.key.toLowerCase() !== 'c' || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
      if (isTypingTarget(event.target) || document.querySelector('[aria-modal="true"]') !== null) return;
      event.preventDefault();
      router.push('/shipments/new');
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [canCreate, onToggleCollapsed, router]);

  const createActive = pathname === '/shipments/new';
  const homeHref = variant === 'admin' ? '/admin' : '/dashboard';

  return (
    <div className="relative flex h-full flex-col">
      {/* Header */}
      <div className={cn('flex h-16 shrink-0 items-center', collapsed ? 'justify-center px-3' : 'px-5')}>
        <Logo href={homeHref} markOnly={collapsed} className="rounded-md" />
        {variant === 'admin' && !collapsed ? (
          <span className="ml-2 rounded-pill bg-accent/20 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.12em] text-accent ring-1 ring-inset ring-accent/30">Admin</span>
        ) : null}
      </div>
      {onToggleCollapsed === undefined ? null : (
        <button
          type="button"
          onClick={onToggleCollapsed}
          aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          aria-expanded={!collapsed}
          className="absolute -right-3 top-5 z-10 grid h-6 w-6 place-items-center rounded-full border border-border bg-surface text-muted-foreground shadow-sm transition-colors hover:border-border-strong hover:text-foreground"
        >
          <ChevronLeft className={cn('h-3.5 w-3.5 transition-transform duration-200 ease-brand', collapsed && 'rotate-180')} aria-hidden="true" />
        </button>
      )}

      <div className={cn('flex min-h-0 flex-1 flex-col gap-5 pb-3', collapsed ? 'px-3' : 'px-4', collapsed ? 'overflow-visible' : 'overflow-y-auto')}>
        {/* Workspace block */}
        {collapsed ? (
          <Tooltip label={tenantName} side="right" className="self-center">
            <span tabIndex={0} className="rounded-md" aria-label={`Workspace ${tenantName}`}>
              <Avatar name={tenantName} size="md" shape="square" />
            </span>
          </Tooltip>
        ) : (
          <div className="flex items-center gap-3 rounded-lg bg-surface-muted p-3">
            <Avatar name={tenantName} size="md" shape="square" />
            <div className="min-w-0">
              <p className="truncate text-[14px] font-semibold text-foreground">{tenantName}</p>
              <p className="truncate text-caption text-muted-foreground">
                {variant === 'admin' ? 'Platform admin' : user === null ? '' : roleLabel(user.role)}
              </p>
            </div>
          </div>
        )}

        {/* Primary action */}
        {canCreate ? (
          collapsed ? (
            <Tooltip label="Create shipment" side="right" className="self-center">
              <Link
                href="/shipments/new"
                aria-label="Create shipment"
                aria-current={createActive ? 'page' : undefined}
                onClick={onNavigate}
                className={cn(buttonVariants({ size: 'md' }), 'h-10 w-10 px-0')}
              >
                <Plus className="h-5 w-5" aria-hidden="true" />
              </Link>
            </Tooltip>
          ) : (
            <Link
              href="/shipments/new"
              aria-current={createActive ? 'page' : undefined}
              onClick={onNavigate}
              className={cn(buttonVariants({ size: 'md' }), 'w-full justify-between pl-3 pr-2')}
            >
              <span className="inline-flex items-center gap-2">
                <Plus className="h-[18px] w-[18px]" aria-hidden="true" />
                Create shipment
              </span>
              {onToggleCollapsed === undefined ? null : (
                <kbd className="hidden rounded-[5px] border border-primary-foreground/30 bg-primary-foreground/15 px-1.5 font-sans text-[11px] font-semibold leading-5 lg:inline" aria-label="Shortcut C">
                  C
                </kbd>
              )}
            </Link>
          )
        ) : null}

        {/* Navigation */}
        <nav aria-label={variant === 'admin' ? 'Admin' : 'Workspace'} className="grid gap-4">
          {groups.map((group) => (
            <div key={group.label}>
              {collapsed ? (
                <div className="mx-auto mb-2 h-px w-6 bg-border" aria-hidden="true" />
              ) : (
                <p className="mb-1.5 px-3 text-[11px] font-semibold uppercase tracking-[0.12em] text-subtle-foreground">{group.label}</p>
              )}
              <ul className="grid gap-0.5">
                {group.items.map((item) => {
                  const active = isActive(item.href, pathname);
                  const Icon = item.icon;
                  const count = badges[item.href] ?? 0;
                  const link = (
                    <Link
                      href={item.href}
                      aria-current={active ? 'page' : undefined}
                      aria-label={collapsed ? (count > 0 ? `${item.label}, ${count} need attention` : item.label) : undefined}
                      onClick={onNavigate}
                      className={cn(
                        'group/nav relative flex h-10 items-center gap-3 rounded-md text-[14px] font-medium transition-colors duration-120',
                        collapsed ? 'w-10 justify-center' : 'px-3',
                        active ? 'bg-primary-soft text-primary' : 'text-muted-foreground hover:bg-surface-muted hover:text-foreground',
                      )}
                    >
                      {active ? (
                        <motion.span
                          layoutId={`${indicatorId}-indicator`}
                          className={cn('absolute top-2 h-6 w-[3px] rounded-r-full bg-primary', collapsed ? '-left-3' : '-left-4')}
                          transition={reduce ? { duration: 0 } : { type: 'spring', stiffness: 500, damping: 40 }}
                          aria-hidden="true"
                        />
                      ) : null}
                      <Icon className="h-[18px] w-[18px] shrink-0" strokeWidth={1.75} aria-hidden="true" />
                      {collapsed ? null : <span className="truncate">{item.label}</span>}
                      {count > 0 ? (
                        collapsed ? (
                          <span className="absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-danger ring-2 ring-surface" aria-hidden="true" />
                        ) : (
                          <span className="ml-auto rounded-pill bg-danger-soft px-1.5 text-[11px] font-semibold leading-5 text-danger">
                            {count}
                            <span className="sr-only"> need attention</span>
                          </span>
                        )
                      ) : null}
                    </Link>
                  );
                  return (
                    <li key={item.href} className={cn(collapsed && 'flex justify-center')}>
                      {collapsed ? (
                        <Tooltip label={item.label} side="right">
                          {link}
                        </Tooltip>
                      ) : (
                        link
                      )}
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </nav>
      </div>

      {/* Footer */}
      <div className={cn('shrink-0 border-t border-border', collapsed ? 'grid grid-cols-1 justify-items-center gap-3 px-3 py-3' : 'grid grid-cols-1 gap-3 p-4')}>
        {collapsed ? (
          <Tooltip label="Contact support" side="right">
            <a
              href={`mailto:${publicEnv.NEXT_PUBLIC_SUPPORT_EMAIL}`}
              aria-label="Contact support"
              className="grid h-10 w-10 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-muted hover:text-foreground"
            >
              <LifeBuoy className="h-[18px] w-[18px]" strokeWidth={1.75} aria-hidden="true" />
            </a>
          </Tooltip>
        ) : (
          <div className="rounded-lg border border-border/60 bg-gradient-to-br from-primary-soft to-transparent p-4">
            <div className="flex items-center gap-2">
              <span className="grid h-8 w-8 place-items-center rounded-md bg-surface text-primary shadow-xs">
                <LifeBuoy className="h-4 w-4" aria-hidden="true" />
              </span>
              <p className="text-small font-semibold">Need help?</p>
            </div>
            <p className="mt-2 text-caption text-muted-foreground">Our team usually replies within one business day.</p>
            <a
              href={`mailto:${publicEnv.NEXT_PUBLIC_SUPPORT_EMAIL}`}
              className={cn(buttonVariants({ variant: 'secondary', size: 'sm' }), 'mt-3 h-8 min-h-8 w-full text-caption')}
            >
              Contact support
            </a>
          </div>
        )}
        {user === null ? null : collapsed ? (
          <UserMenu placement="top-start" workspaceLinks={variant === 'app'} trigger={<Avatar name={user.name} size="md" />} />
        ) : (
          <div className="flex items-center gap-3 rounded-lg px-1">
            <Avatar name={user.name} size="md" />
            <div className="min-w-0 flex-1">
              <p className="truncate text-small font-semibold">{user.name}</p>
              <p className="truncate text-caption text-muted-foreground">{user.email}</p>
            </div>
            <UserMenu
              placement="top-start"
              workspaceLinks={variant === 'app'}
              label="Open account menu"
              trigger={
                <span className="grid h-8 w-8 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-muted hover:text-foreground">
                  <MoreHorizontal className="h-4 w-4" aria-hidden="true" />
                </span>
              }
            />
          </div>
        )}
      </div>
    </div>
  );
}
