import React, { useState, useEffect, useCallback } from 'react';

const recentItems = [
  { type: 'channel', id: 'general', name: 'general', server: 'AeThex Foundation', icon: '#' },
  { type: 'dm', id: 'dm-1', name: 'Trevor', avatar: 'T', color: '#ff0000' },
  { type: 'channel', id: 'api-discussion', name: 'api-discussion', server: 'AeThex Foundation', icon: '#' },
];

const allItems = [
  // Channels
  { type: 'channel', id: 'general', name: 'general', server: 'AeThex Foundation', icon: '#' },
  { type: 'channel', id: 'updates', name: 'updates', server: 'AeThex Foundation', icon: '📢' },
  { type: 'channel', id: 'api-discussion', name: 'api-discussion', server: 'AeThex Foundation', icon: '#' },
  { type: 'channel', id: 'bug-reports', name: 'bug-reports', server: 'AeThex Foundation', icon: '🐛' },
  { type: 'channel', id: 'nexus-lounge', name: 'Nexus Lounge', server: 'AeThex Foundation', icon: '🔊', isVoice: true },
  { type: 'channel', id: 'labs-general', name: 'general', server: 'AeThex Labs', icon: '#' },
  { type: 'channel', id: 'experiments', name: 'experiments', server: 'AeThex Labs', icon: '🧪' },
  // Users/DMs
  { type: 'user', id: 'u-1', name: 'Trevor', tag: '#0001', avatar: 'T', color: '#ff0000' },
  { type: 'user', id: 'u-2', name: 'Sarah', tag: '#0042', avatar: 'S', color: '#ffa500' },
  { type: 'user', id: 'u-3', name: 'Marcus', tag: '#1234', avatar: 'M', color: '#0066ff' },
  { type: 'user', id: 'u-4', name: 'Anderson', tag: '#0001', avatar: 'A', color: '#5865f2' },
  // Servers
  { type: 'server', id: 's-1', name: 'AeThex Foundation', icon: 'F', color: '#ff0000' },
  { type: 'server', id: 's-2', name: 'AeThex Labs', icon: 'L', color: '#ffa500' },
  { type: 'server', id: 's-3', name: 'AeThex Corporation', icon: 'C', color: '#0066ff' },
];

export default function QuickSwitcher({ onSelect, onClose }) {
  const [query, setQuery] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [filter, setFilter] = useState('all'); // all, channels, users, servers

  const getFilteredItems = useCallback(() => {
    let items = query ? allItems : recentItems;
    
    if (query) {
      const lowerQuery = query.toLowerCase();
      items = items.filter(item => 
        item.name.toLowerCase().includes(lowerQuery) ||
        (item.server && item.server.toLowerCase().includes(lowerQuery))
      );
    }

    if (filter !== 'all') {
      const typeMap = {
        channels: 'channel',
        users: ['user', 'dm'],
        servers: 'server',
      };
      const types = typeMap[filter];
      items = items.filter(item => 
        Array.isArray(types) ? types.includes(item.type) : item.type === types
      );
    }

    return items.slice(0, 10);
  }, [query, filter]);

  const filteredItems = getFilteredItems();

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

  const handleKeyDown = useCallback((e) => {
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setSelectedIndex(prev => Math.min(prev + 1, filteredItems.length - 1));
        break;
      case 'ArrowUp':
        e.preventDefault();
        setSelectedIndex(prev => Math.max(prev - 1, 0));
        break;
      case 'Enter':
        e.preventDefault();
        if (filteredItems[selectedIndex]) {
          onSelect?.(filteredItems[selectedIndex]);
          onClose?.();
        }
        break;
      case 'Escape':
        e.preventDefault();
        onClose?.();
        break;
      case 'Tab':
        e.preventDefault();
        // Cycle through filters
        const filters = ['all', 'channels', 'users', 'servers'];
        const currentIdx = filters.indexOf(filter);
        setFilter(filters[(currentIdx + 1) % filters.length]);
        break;
    }
  }, [filteredItems, selectedIndex, filter, onSelect, onClose]);

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  const getItemIcon = (item) => {
    if (item.type === 'channel') {
      return item.isVoice ? '🔊' : item.icon;
    }
    if (item.type === 'user' || item.type === 'dm') {
      return (
        <div 
          className="qs-avatar"
          style={item.color ? { background: item.color } : undefined}
        >
          {item.avatar}
        </div>
      );
    }
    if (item.type === 'server') {
      return (
        <div 
          className="qs-server-icon"
          style={item.color ? { background: item.color } : undefined}
        >
          {item.icon}
        </div>
      );
    }
  };

  return (
    <div className="modal-overlay dark" onClick={onClose}>
      <div className="quick-switcher" onClick={(e) => e.stopPropagation()}>
        <div className="qs-search">
          <input
            type="text"
            placeholder="Where would you like to go?"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            autoFocus
          />
        </div>

        <div className="qs-filters">
          <button 
            className={`qs-filter ${filter === 'all' ? 'active' : ''}`}
            onClick={() => setFilter('all')}
          >
            All
          </button>
          <button 
            className={`qs-filter ${filter === 'channels' ? 'active' : ''}`}
            onClick={() => setFilter('channels')}
          >
            # Channels
          </button>
          <button 
            className={`qs-filter ${filter === 'users' ? 'active' : ''}`}
            onClick={() => setFilter('users')}
          >
            @ Users
          </button>
          <button 
            className={`qs-filter ${filter === 'servers' ? 'active' : ''}`}
            onClick={() => setFilter('servers')}
          >
            🏠 Servers
          </button>
        </div>

        <div className="qs-results">
          {!query && (
            <div className="qs-section-header">Recent</div>
          )}
          {filteredItems.map((item, idx) => (
            <div
              key={item.id}
              className={`qs-item ${idx === selectedIndex ? 'selected' : ''}`}
              onClick={() => {
                onSelect?.(item);
                onClose?.();
              }}
              onMouseEnter={() => setSelectedIndex(idx)}
            >
              <span className="qs-icon">{getItemIcon(item)}</span>
              <div className="qs-item-info">
                <span className="qs-item-name">{item.name}</span>
                {item.tag && <span className="qs-item-tag">{item.tag}</span>}
                {item.server && <span className="qs-item-server">{item.server}</span>}
              </div>
              {item.type === 'channel' && <span className="qs-type">#</span>}
              {item.type === 'user' && <span className="qs-type">@</span>}
            </div>
          ))}
          {filteredItems.length === 0 && (
            <div className="qs-empty">
              <p>No results found</p>
            </div>
          )}
        </div>

        <div className="qs-footer">
          <span className="qs-hint">
            <kbd>↑</kbd><kbd>↓</kbd> to navigate
          </span>
          <span className="qs-hint">
            <kbd>Enter</kbd> to select
          </span>
          <span className="qs-hint">
            <kbd>Tab</kbd> to filter
          </span>
          <span className="qs-hint">
            <kbd>Esc</kbd> to close
          </span>
        </div>
      </div>
    </div>
  );
}
