import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ChevronDown, X } from 'lucide-react';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';

interface FilterPickerFieldProps {
  value: string;
  options: string[];
  placeholder?: string;
  ariaLabel?: string;
  onChange: (value: string) => void;
}

export function FilterPickerField({
  value,
  options,
  placeholder = '请选择',
  ariaLabel = '筛选选择',
  onChange,
}: FilterPickerFieldProps) {
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(false);
  const [query, setQuery] = useState('');
  const fieldRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!editing) setQuery(value);
  }, [value, editing]);

  const dismiss = useCallback(() => {
    setOpen(false);
    setEditing(false);
    setQuery(value);
  }, [value]);

  useDismissOnFocusOutside(open, fieldRef, dismiss);

  const filtered = useMemo(() => {
    const q = query.trim();
    if (!q) return options;
    return options.filter((item) => item.includes(q));
  }, [options, query]);

  const pick = (next: string) => {
    onChange(next);
    setQuery(next);
    setOpen(false);
    setEditing(false);
    inputRef.current?.blur();
  };

  const clear = (event: React.MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    onChange('');
    setQuery('');
    setOpen(false);
    setEditing(false);
    inputRef.current?.focus();
  };

  const startEdit = () => {
    setEditing(true);
    setOpen(true);
    setQuery(value);
    window.requestAnimationFrame(() => inputRef.current?.select());
  };

  return (
    <div className="vm-filter-picker-field" ref={fieldRef}>
      <div className={`vm-filter-picker-control ${open ? 'open' : ''}`}>
        <input
          ref={inputRef}
          type="text"
          className="vm-filter-picker-input"
          value={editing ? query : value}
          placeholder={placeholder}
          aria-label={ariaLabel}
          aria-expanded={open}
          aria-autocomplete="list"
          role="combobox"
          readOnly={!editing}
          onFocus={startEdit}
          onChange={(event) => {
            setQuery(event.target.value);
            setOpen(true);
          }}
          onKeyDown={(event) => {
            if (event.key === 'Escape') dismiss();
          }}
        />
        {value ? (
          <button
            type="button"
            className="vm-filter-picker-clear"
            onClick={clear}
            aria-label={`清空${ariaLabel}`}
            tabIndex={-1}
          >
            <X size={14} aria-hidden />
          </button>
        ) : null}
        <ChevronDown size={14} className="vm-filter-picker-chevron" aria-hidden />
      </div>

      {open && (
        <div className="vm-filter-picker-popover" role="listbox" aria-label={ariaLabel}>
          <div className="vm-filter-picker-options">
            {filtered.length === 0 ? (
              <p className="vm-filter-picker-empty">暂无匹配项</p>
            ) : (
              filtered.map((item) => (
                <button
                  key={item}
                  type="button"
                  role="option"
                  aria-selected={value === item}
                  className={`vm-filter-picker-option ${value === item ? 'checked' : ''}`}
                  onMouseDown={(event) => event.preventDefault()}
                  onClick={() => pick(item)}
                >
                  {item}
                </button>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}
