import { useState, type ReactNode } from 'react';
import { cn } from '../lib/cn';

export interface SidebarItem {
  label: string;
  href?: string;
  icon?: ReactNode;
  active?: boolean;
  items?: SidebarItem[];
}

export interface SidebarProps {
  brand?: ReactNode;
  items: SidebarItem[];
  collapsible?: boolean;
  defaultCollapsed?: boolean;
  className?: string;
}

export function Sidebar({
  brand,
  items,
  collapsible = true,
  defaultCollapsed = false,
  className,
}: SidebarProps) {
  const [collapsed, setCollapsed] = useState(defaultCollapsed);

  return (
    <aside
      className={cn(
        'flex flex-col bg-surface border-r border-border transition-all duration-base',
        collapsed ? 'w-16' : 'w-64',
        className
      )}
    >
      <div className="flex h-16 items-center justify-between px-4 border-b border-border">
        {!collapsed && brand && <div className="text-text font-semibold truncate">{brand}</div>}
        {collapsible && (
          <button
            type="button"
            aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
            onClick={() => setCollapsed((v) => !v)}
            className="inline-flex h-8 w-8 items-center justify-center rounded-md text-text-2 hover:text-text hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-ring"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              {collapsed ? <polyline points="9 18 15 12 9 6" /> : <polyline points="15 18 9 12 15 6" />}
            </svg>
          </button>
        )}
      </div>

      <nav className="flex-1 overflow-y-auto py-2">
        <ul className="flex flex-col gap-0.5 px-2">
          {items.map((item, i) => (
            <SidebarNode key={i} item={item} collapsed={collapsed} />
          ))}
        </ul>
      </nav>
    </aside>
  );
}

function SidebarNode({ item, collapsed }: { item: SidebarItem; collapsed: boolean }) {
  const [open, setOpen] = useState(true);
  const hasChildren = !!item.items?.length;

  if (hasChildren) {
    return (
      <li>
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          aria-expanded={open}
          className={cn(
            'w-full flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors',
            'text-text-3 hover:text-text-2',
            collapsed && 'justify-center'
          )}
        >
          {item.icon && <span className="shrink-0">{item.icon}</span>}
          {!collapsed && (
            <>
              <span className="flex-1 text-left truncate uppercase text-xs tracking-wider">{item.label}</span>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className={cn('transition-transform', open && 'rotate-90')}>
                <polyline points="9 18 15 12 9 6" />
              </svg>
            </>
          )}
        </button>
        {open && !collapsed && (
          <ul className="flex flex-col gap-0.5 ml-3 mt-0.5 border-l border-border pl-2">
            {item.items!.map((child, i) => (
              <SidebarNode key={i} item={child} collapsed={false} />
            ))}
          </ul>
        )}
      </li>
    );
  }

  return (
    <li>
      <a
        href={item.href || '#'}
        aria-current={item.active ? 'page' : undefined}
        title={collapsed ? item.label : undefined}
        className={cn(
          'flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors',
          item.active
            ? 'bg-primary-soft text-primary-deep font-medium'
            : 'text-text-2 hover:text-text hover:bg-surface-2',
          collapsed && 'justify-center'
        )}
      >
        {item.icon && <span className="shrink-0">{item.icon}</span>}
        {!collapsed && <span className="flex-1 truncate">{item.label}</span>}
      </a>
    </li>
  );
}
