'use client';

import { useEffect, useRef, useState } from 'react';
import type { Project } from '../../lib/types';

interface ProjectSwitcherProps {
  open: boolean;
  projects: Project[];
  onSelect: (projectId: string | undefined) => void;
  onClose: () => void;
}

export function ProjectSwitcher({ open, projects, onSelect, onClose }: ProjectSwitcherProps) {
  const [query, setQuery] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (open) {
      setQuery('');
      setSelectedIndex(0);
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open]);

  if (!open) return null;

  const allOption = { id: '', name: 'All Conversations', icon: '📂' };
  const items = [allOption, ...projects].filter(p =>
    p.name.toLowerCase().includes(query.toLowerCase())
  );

  const handleSelect = (id: string) => {
    onSelect(id || undefined);
    onClose();
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setSelectedIndex(i => Math.min(i + 1, items.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setSelectedIndex(i => Math.max(i - 1, 0));
    } else if (e.key === 'Enter' && items[selectedIndex]) {
      handleSelect(items[selectedIndex].id);
    } else if (e.key === 'Escape') {
      onClose();
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center pt-[20vh] bg-black/50"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md rounded-lg border border-white/10 bg-[var(--bg-elevated)] shadow-2xl"
        onClick={e => e.stopPropagation()}
      >
        <div className="border-b border-white/10 p-3">
          <input
            ref={inputRef}
            value={query}
            onChange={e => {
              setQuery(e.target.value);
              setSelectedIndex(0);
            }}
            onKeyDown={handleKeyDown}
            placeholder="Switch project..."
            className="w-full bg-transparent text-sm text-[var(--text-primary)] outline-none placeholder:text-[var(--text-tertiary)]"
          />
        </div>
        <div className="max-h-64 overflow-auto p-1">
          {items.map((item, idx) => (
            <button
              key={item.id || '__all'}
              type="button"
              onClick={() => handleSelect(item.id)}
              className={`flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm ${idx === selectedIndex ? 'bg-white/10 text-[var(--text-primary)]' : 'text-[var(--text-secondary)] hover:bg-white/5'}`}
            >
              <span>{item.icon}</span>
              <span>{item.name}</span>
            </button>
          ))}
          {items.length === 0 && (
            <p className="px-3 py-2 text-xs text-[var(--text-tertiary)]">No projects found</p>
          )}
        </div>
      </div>
    </div>
  );
}
