import React, { useState, useMemo } from 'react';
import { Search, Check } from 'lucide-react';
import { cn } from '../lib/utils';

interface ColumnFilterPopoverProps {
  uniqueValues: string[];
  selectedValues: string[];
  onToggle: (val: string) => void;
  onSelectAll: (vals: string[]) => void;
  onClear: () => void;
  onClose: () => void;
  title?: string;
  className?: string;
}

export function ColumnFilterPopover({
  uniqueValues,
  selectedValues,
  onToggle,
  onSelectAll,
  onClear,
  onClose,
  title,
  className
}: ColumnFilterPopoverProps) {
  const [search, setSearch] = useState('');
  
  const filteredValues = useMemo(() => {
    return uniqueValues.filter(v => 
      String(v || '').toLowerCase().includes(search.toLowerCase())
    );
  }, [uniqueValues, search]);

  const isAllSelected = selectedValues.length === uniqueValues.length && uniqueValues.length > 0;

  return (
    <div
      className={cn(
        "absolute top-full left-0 mt-1 w-64 bg-slate-800 border border-slate-700 rounded-lg shadow-2xl z-50 p-3 flex flex-col gap-3 animate-in fade-in zoom-in-95 duration-100",
        className
      )}
      onClick={(e) => e.stopPropagation()}
    >
      {title && <div className="text-[10px] font-bold text-slate-500 uppercase tracking-wider px-1">{title}</div>}
      
      <div className="relative">
        <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-500" />
        <input
          type="text"
          placeholder="Filter values..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          className="w-full bg-slate-900 border border-slate-700 rounded p-1.5 pl-8 text-xs text-white focus:outline-none focus:border-blue-500"
          autoFocus
        />
      </div>

      <div className="max-h-48 overflow-y-auto space-y-0.5 pr-1 custom-scrollbar">
        {filteredValues.map(val => (
          <div
            key={val}
            role="checkbox"
            aria-checked={selectedValues.includes(val)}
            tabIndex={0}
            onClick={() => onToggle(val)}
            onKeyDown={(e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); onToggle(val); } }}
            className="flex items-center gap-2 p-1.5 hover:bg-slate-700/50 rounded cursor-pointer group"
          >
            <div className={cn(
              "w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors",
              selectedValues.includes(val) ? "bg-blue-600 border-blue-600" : "border-slate-600 bg-slate-900 group-hover:border-slate-500"
            )}>
              {selectedValues.includes(val) && <Check className="w-3 h-3 text-white" />}
            </div>
            <span className="text-xs text-slate-300 truncate" title={val}>{val || '(Empty)'}</span>
          </div>
        ))}
        {filteredValues.length === 0 && (
          <div className="text-[10px] text-slate-500 text-center py-4 italic">No values found</div>
        )}
      </div>

      <div className="flex items-center justify-between pt-2 border-t border-slate-700 mt-1">
        <div className="flex items-center gap-3">
          <button
            onClick={() => {
              if (isAllSelected) {
                onSelectAll([]);
              } else {
                onSelectAll(uniqueValues);
              }
            }}
            className="text-[10px] font-black text-indigo-400 hover:text-indigo-300 transition-colors uppercase tracking-tight"
          >
            {isAllSelected ? 'Deselect All' : 'Select All'}
          </button>
          <span className="text-slate-600 font-bold">•</span>
          <button
            onClick={onClear}
            className="text-[10px] font-bold text-slate-400 hover:text-white transition-colors uppercase tracking-tight"
          >
            Clear Current
          </button>
        </div>
        <button
          onClick={onClose}
          className="px-4 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-[10px] font-black rounded transition-colors shadow-lg active:scale-95 uppercase"
        >
          OK
        </button>
      </div>
    </div>
  );
}
