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

interface User {
  id: string;
  username: string;
  display_name: string;
}

interface MentionPopupProps {
  users: User[];
  filter: string;
  onSelect: (user: User) => void;
  position: { top: number; left: number };
}

export function MentionPopup({ users, filter, onSelect, position }: MentionPopupProps) {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const listRef = useRef<HTMLDivElement>(null);

  const filtered = users.filter(u =>
    u.username.toLowerCase().includes(filter.toLowerCase()) ||
    u.display_name?.toLowerCase().includes(filter.toLowerCase())
  ).slice(0, 8);

  useEffect(() => {
    setSelectedIndex(0);
  }, [filter]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setSelectedIndex(prev => Math.min(prev + 1, filtered.length - 1));
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        setSelectedIndex(prev => Math.max(prev - 1, 0));
      } else if (e.key === 'Enter' || e.key === 'Tab') {
        e.preventDefault();
        if (filtered[selectedIndex]) {
          onSelect(filtered[selectedIndex]);
        }
      } else if (e.key === 'Escape') {
        e.preventDefault();
        onSelect(null as any);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [filtered, selectedIndex, onSelect]);

  if (filtered.length === 0) return null;

  return (
    <div
      ref={listRef}
      className="absolute bg-gb-bg border border-gb-bg-t shadow-lg z-50 min-w-[200px] max-h-[200px] overflow-y-auto"
      style={{ bottom: '100%', left: position.left, marginBottom: 4 }}
    >
      <div className="px-2 py-1 text-xs text-gb-fg-f font-mono border-b border-gb-bg-t">
        MEMBERS
      </div>
      {filtered.map((user, index) => (
        <button
          key={user.id}
          onClick={() => onSelect(user)}
          onMouseEnter={() => setSelectedIndex(index)}
          className={`
            w-full px-2 py-1 text-left text-xs font-mono flex items-center gap-2
            transition-colors
            ${index === selectedIndex
              ? 'bg-gb-orange text-gb-bg'
              : 'text-gb-fg hover:bg-gb-bg-s'
            }
          `}
        >
          <span className="text-gb-green">●</span>
          <span>{user.display_name || user.username}</span>
          {user.display_name && user.display_name !== user.username && (
            <span className="text-gb-fg-f">({user.username})</span>
          )}
        </button>
      ))}
    </div>
  );
}
