import { useEffect, useState } from 'react';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { type ChatInputRegistration } from '@/lib/events';

interface FloatingMenuProps {
  x: number;
  y: number;
  hasSelection: boolean;
  chatInputs: ChatInputRegistration[];
  onCopy: () => void;
  onPaste: () => void;
  onSelectAll: () => void;
  onSearch: () => void;
  onSendToChat: (chatId: string) => void;
  onDismiss: () => void;
}
export function FloatingMenu({
  x,
  y,
  hasSelection,
  chatInputs,
  onCopy,
  onPaste,
  onSelectAll,
  onSearch,
  onSendToChat,
  onDismiss,
}: FloatingMenuProps) {
  const [submenu, setSubmenu] = useState(false);
  const MENU_W = 200;
  const MENU_H = 220;
  const left = Math.min(x, window.innerWidth - MENU_W - 8);
  const top = Math.min(y, window.innerHeight - MENU_H - 8);

  useEffect(() => {
    function onKey(ev: KeyboardEvent): void {
      if (ev.key === 'Escape') onDismiss();
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onDismiss]);

  const flatChat = chatInputs.length === 1 ? chatInputs[0] : null;

  return (
    <div
      data-term-menu="1"
      role="menu"
      style={{
        position: 'fixed',
        top,
        left,
        background: '#1a1d24',
        border: '1px solid #2a2d34',
        borderRadius: 8,
        padding: 4,
        fontSize: 14,
        minWidth: MENU_W,
        boxShadow: '0 8px 24px rgba(0,0,0,0.5)',
        zIndex: 50,
        color: '#d6deeb',
      }}
    >
      <MenuItem disabled={!hasSelection} onClick={onCopy}>Copy</MenuItem>
      <MenuItem onClick={onPaste}>Paste</MenuItem>
      <MenuItem onClick={onSelectAll}>Select All</MenuItem>
      <MenuItem onClick={onSearch}>Search</MenuItem>
      {flatChat && (
        <MenuItem disabled={!hasSelection} onClick={() => onSendToChat(flatChat.chatId)}>
          Send to {flatChat.label}
        </MenuItem>
      )}
      {chatInputs.length > 1 && (
        <div>
          <button
            type="button"
            disabled={!hasSelection}
            onClick={() => setSubmenu((v) => !v)}
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              width: '100%',
              padding: '10px 12px',
              minHeight: 44,
              background: 'transparent',
              border: 0,
              color: hasSelection ? '#d6deeb' : '#575656',
              cursor: hasSelection ? 'pointer' : 'not-allowed',
              borderRadius: 6,
              textAlign: 'left',
            }}
          >
            <span>Send to chat</span>
            {submenu ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
          </button>
          {submenu && hasSelection && (
            <div style={{ paddingLeft: 8 }}>
              {chatInputs.map((c) => (
                <MenuItem key={c.chatId} onClick={() => onSendToChat(c.chatId)}>
                  {c.label}
                </MenuItem>
              ))}
            </div>
          )}
        </div>
      )}
      <div style={{ height: 1, background: '#2a2d34', margin: '4px 0' }} />
      <MenuItem onClick={onDismiss}>Dismiss</MenuItem>
    </div>
  );
}

function MenuItem({
  children,
  onClick,
  disabled = false,
}: {
  children: React.ReactNode;
  onClick: () => void;
  disabled?: boolean;
}) {
  return (
    <button
      type="button"
      role="menuitem"
      disabled={disabled}
      onClick={onClick}
      style={{
        display: 'block',
        width: '100%',
        padding: '10px 12px',
        minHeight: 44,
        background: 'transparent',
        border: 0,
        color: disabled ? '#575656' : '#d6deeb',
        cursor: disabled ? 'not-allowed' : 'pointer',
        textAlign: 'left',
        borderRadius: 6,
        fontSize: 14,
      }}
      onMouseEnter={(ev) => {
        if (!disabled) (ev.currentTarget as HTMLButtonElement).style.background = '#2a2d34';
      }}
      onMouseLeave={(ev) => {
        (ev.currentTarget as HTMLButtonElement).style.background = 'transparent';
      }}
    >
      {children}
    </button>
  );
}
