import { useState, useRef, useEffect } from 'react';
import { Icons } from '../icons/Icons';

export default function SearchSelect({ value, onChange, options, placeholder = 'Search...', renderOption, renderSelected, className = '' }) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const ref = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  const filtered = options.filter((opt) => {
    if (!query.trim()) return true;
    const q = query.toLowerCase();
    return (opt.searchText || opt.label || '').toLowerCase().includes(q);
  });

  const selected = options.find((o) => o.value === value);

  const handleSelect = (val) => {
    onChange(val);
    setOpen(false);
    setQuery('');
  };

  const handleClear = (e) => {
    e.stopPropagation();
    onChange('');
    setQuery('');
  };

  return (
    <div className={`relative ${className}`} ref={ref}>
      {/* Trigger */}
      <div
        className="flex items-center gap-1.5 bg-s2 border border-bd rounded-md px-2.5 py-1.5 cursor-pointer hover:border-ac/50 transition-colors min-h-[34px]"
        onClick={() => setOpen(!open)}
      >
        {selected ? (
          <div className="flex-1 text-[13px] truncate">
            {renderSelected ? renderSelected(selected) : <span className="text-t1">{selected.label}</span>}
          </div>
        ) : (
          <span className="flex-1 text-[13px] text-t3">{placeholder}</span>
        )}
        {value ? (
          <span className="text-t3 hover:text-rd flex-shrink-0" onClick={handleClear}><Icons.X /></span>
        ) : (
          <span className="text-t3 text-[9px] flex-shrink-0">▼</span>
        )}
      </div>

      {/* Dropdown */}
      {open && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-s1 border border-bd rounded-md shadow-lg z-50 max-h-[260px] flex flex-col">
          {/* Search input */}
          <div className="flex items-center gap-1.5 px-2.5 py-2 border-b border-bd flex-shrink-0">
            <Icons.Search />
            <input
              ref={inputRef}
              className="bg-transparent border-none text-t1 text-[13px] w-full outline-none"
              placeholder={placeholder}
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Escape') setOpen(false);
                if (e.key === 'Enter' && filtered.length === 1) handleSelect(filtered[0].value);
              }}
            />
            {query && <span className="text-t3 hover:text-t1 cursor-pointer flex-shrink-0" onClick={() => setQuery('')}><Icons.X /></span>}
          </div>

          {/* Options list */}
          <div className="overflow-auto flex-1">
            {filtered.length === 0 ? (
              <div className="text-center text-t3 text-xs py-4">No results found</div>
            ) : (
              filtered.map((opt) => (
                <div
                  key={opt.value}
                  className={`px-2.5 py-2 cursor-pointer text-[13px] transition-colors border-b border-bd/50 last:border-0 ${
                    opt.value === value ? 'bg-ac/10 text-ac' : 'text-t1 hover:bg-s2'
                  }`}
                  onClick={() => handleSelect(opt.value)}
                >
                  {renderOption ? renderOption(opt) : opt.label}
                </div>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}
