import { useState, useRef, useEffect } from 'react';

export interface MenuItem {
  label?: string;
  type?: 'separator' | 'checkbox' | 'radio';
  shortcut?: string;
  action?: string;
  checked?: boolean;
  group?: string;
  children?: MenuItem[];
  disabled?: boolean;
}

interface MenuBarProps {
  menus: Record<string, MenuItem[]>;
  onAction: (action: string) => void;
  checkedItems?: Set<string>;
}

const menuBarStyle: React.CSSProperties = {
  height: 24, display: 'flex', alignItems: 'center',
  background: '#f0f0f0', borderBottom: '1px solid #c0c0c0',
  fontFamily: 'system-ui, sans-serif', fontSize: 13, color: '#1a1a1a',
  flexShrink: 0, userSelect: 'none', zIndex: 100,
};

export function MenuBar({ menus, onAction, checkedItems }: MenuBarProps) {
  const [openMenu, setOpenMenu] = useState<string | null>(null);
  const [subMenu, setSubMenu] = useState<string | null>(null);
  const barRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const close = (e: MouseEvent) => {
      if (barRef.current && !barRef.current.contains(e.target as Node)) {
        setOpenMenu(null); setSubMenu(null);
      }
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  return (
    <div ref={barRef} data-testid="menu-bar" style={menuBarStyle}>
      {Object.entries(menus).map(([name, items]) => (
        <div key={name} style={{ position: 'relative' }}>
          <div
            data-testid={`menu-${name}`}
            onClick={() => setOpenMenu(openMenu === name ? null : name)}
            onMouseEnter={() => openMenu && setOpenMenu(name)}
            style={{
              padding: '2px 10px', cursor: 'pointer',
              background: openMenu === name ? '#cce4f7' : 'transparent',
            }}
          >
            {name}
          </div>
          {openMenu === name && (
            <DropdownMenu items={items} onAction={(a) => { onAction(a); setOpenMenu(null); setSubMenu(null); }}
              checkedItems={checkedItems} subMenu={subMenu} setSubMenu={setSubMenu} />
          )}
        </div>
      ))}
    </div>
  );
}

function DropdownMenu({ items, onAction, checkedItems, subMenu, setSubMenu }: {
  items: MenuItem[]; onAction: (a: string) => void; checkedItems?: Set<string>;
  subMenu: string | null; setSubMenu: (s: string | null) => void;
}) {
  return (
    <div style={{
      position: 'absolute', top: '100%', left: 0, minWidth: 220,
      background: '#f8f8f8', border: '1px solid #c0c0c0', boxShadow: '2px 2px 6px rgba(0,0,0,0.15)',
      zIndex: 200, padding: '2px 0',
    }}>
      {items.map((item, i) => {
        if (item.type === 'separator') return <div key={i} style={{ height: 1, background: '#d0d0d0', margin: '3px 4px' }} />;
        if (item.children) {
          return (
            <div key={i} style={{ position: 'relative' }}
              onMouseEnter={() => setSubMenu(item.label || '')}
              onMouseLeave={() => setSubMenu(null)}
            >
              <div style={{
                padding: '3px 24px 3px 28px', cursor: 'pointer', display: 'flex', justifyContent: 'space-between',
                background: subMenu === item.label ? '#cce4f7' : 'transparent',
              }}>
                <span>{item.label}</span><span style={{ color: '#888' }}>▶</span>
              </div>
              {subMenu === item.label && (
                <div style={{
                  position: 'absolute', left: '100%', top: -2, minWidth: 200,
                  background: '#f8f8f8', border: '1px solid #c0c0c0', boxShadow: '2px 2px 6px rgba(0,0,0,0.15)',
                  padding: '2px 0', zIndex: 201,
                }}>
                  {item.children.map((child, j) => (
                    <MenuItemRow key={j} item={child} onAction={onAction} checkedItems={checkedItems} />
                  ))}
                </div>
              )}
            </div>
          );
        }
        return <MenuItemRow key={i} item={item} onAction={onAction} checkedItems={checkedItems} />;
      })}
    </div>
  );
}

function MenuItemRow({ item, onAction, checkedItems }: { item: MenuItem; onAction: (a: string) => void; checkedItems?: Set<string> }) {
  const isChecked = item.action ? checkedItems?.has(item.action) : false;
  const isDisabled = item.disabled && !item.action;
  return (
    <div
      data-checked={isChecked ? 'true' : 'false'}
      data-disabled={isDisabled ? 'true' : 'false'}
      onClick={() => !isDisabled && item.action && onAction(item.action)}
      title={isDisabled ? 'Not yet implemented' : undefined}
      style={{
        padding: '3px 24px 3px 28px', cursor: isDisabled ? 'default' : 'pointer',
        display: 'flex', justifyContent: 'space-between', position: 'relative',
        color: isDisabled ? '#aaa' : '#1a1a1a',
      }}
      onMouseEnter={(e) => { if (!isDisabled) e.currentTarget.style.background = '#cce4f7'; }}
      onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
    >
      {(item.type === 'checkbox' || item.type === 'radio') && (
        <span style={{ position: 'absolute', left: 8, fontSize: 12 }}>
          {isChecked ? (item.type === 'radio' ? '●' : '✓') : ''}
        </span>
      )}
      <span>{item.label}</span>
      {item.shortcut && <span style={{ color: '#999', fontSize: 11, marginLeft: 16 }}>{item.shortcut}</span>}
    </div>
  );
}
