import { useState, useRef, useEffect } from 'react';
import type { FilterState } from '../types/project';

interface FilterToolbarProps {
  query: string;
  selectedTags: string[];
  availableTags: string[];
  sort: FilterState['sort'];
  projectCount: number;
  onSearchChange: (query: string) => void;
  onTagsChange: (tags: string[]) => void;
  onSortChange: (sort: FilterState['sort']) => void;
}

const sortOptions: { value: FilterState['sort']; label: string }[] = [
  { value: 'stars', label: 'Most Stars' },
  { value: 'alphabetical', label: 'Alphabetical' }
];

export default function FilterToolbar({
  query,
  selectedTags,
  availableTags,
  sort,
  projectCount,
  onSearchChange,
  onTagsChange,
  onSortChange
}: FilterToolbarProps) {
  const [showTagDropdown, setShowTagDropdown] = useState(false);
  const searchRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === '/' && document.activeElement?.tagName !== 'INPUT') {
        e.preventDefault();
        searchRef.current?.focus();
      }
      if (e.key === 'Escape') {
        setShowTagDropdown(false);
      }
    };
    
    const handleClickOutside = (e: MouseEvent) => {
      // Check if click is outside the dropdown
      const target = e.target as HTMLElement;
      if (!target.closest('.tag-dropdown-container')) {
        setShowTagDropdown(false);
      }
    };
    
    window.addEventListener('keydown', handleKeyDown);
    if (showTagDropdown) {
      document.addEventListener('click', handleClickOutside);
    }
    
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      document.removeEventListener('click', handleClickOutside);
    };
  }, [showTagDropdown]);

  const toggleTag = (tag: string) => {
    if (selectedTags.includes(tag)) {
      onTagsChange(selectedTags.filter(t => t !== tag));
    } else {
      onTagsChange([...selectedTags, tag]);
    }
  };

  return (
    <div className="mb-6 space-y-4">
      <div className="flex flex-wrap gap-3 items-center">
        <div className="relative flex-1 min-w-[200px] max-w-md">
          <input
            ref={searchRef}
            type="text"
            value={query}
            onChange={(e) => onSearchChange(e.target.value)}
            placeholder="Search projects or tags"
            className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 placeholder-gray-500 focus:outline-none focus:border-blue-500"
          />
          <svg className="absolute left-3 top-2.5 w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </div>

        <select
          value={sort}
          onChange={(e) => onSortChange(e.target.value as FilterState['sort'])}
          className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 focus:outline-none focus:border-blue-500"
        >
          {sortOptions.map(option => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>

        <div className="relative tag-dropdown-container">
          <button
            onClick={() => setShowTagDropdown(!showTagDropdown)}
            className="px-4 py-2 bg-gray-800 border border-gray-700 rounded-lg text-gray-100 hover:bg-gray-700 focus:outline-none focus:border-blue-500 flex items-center gap-2"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
            </svg>
            Tags {selectedTags.length > 0 && `(${selectedTags.length})`}
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
          
          {showTagDropdown && (
            <div className="absolute top-full mt-2 w-64 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-20 max-h-80 overflow-y-auto">
              <div className="p-2">
                {availableTags.map(tag => (
                  <label key={tag} className="flex items-center px-2 py-1.5 hover:bg-gray-700 rounded cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedTags.includes(tag)}
                      onChange={() => toggleTag(tag)}
                      className="mr-2 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500"
                    />
                    <span className="text-sm text-gray-200">{tag}</span>
                  </label>
                ))}
              </div>
            </div>
          )}
        </div>

        <span className="text-sm text-gray-400">
          Showing {projectCount} projects
        </span>
      </div>

      {selectedTags.length > 0 && (
        <div className="flex flex-wrap gap-2">
          {selectedTags.map(tag => (
            <span
              key={tag}
              className="inline-flex items-center gap-1 px-3 py-1 bg-blue-900 text-blue-200 rounded-full text-sm"
            >
              {tag}
              <button
                onClick={() => toggleTag(tag)}
                className="hover:text-white"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </span>
          ))}
          <button
            onClick={() => onTagsChange([])}
            className="text-sm text-gray-400 hover:text-gray-200"
          >
            Clear all
          </button>
        </div>
      )}
    </div>
  );
}