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

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

export function MultiSelectField({
  values,
  options,
  placeholder = '请选择',
  ariaLabel,
  onChange,
}: MultiSelectFieldProps) {
  const [open, setOpen] = useState(false);
  const fieldRef = useRef<HTMLDivElement>(null);

  const dismiss = useCallback(() => setOpen(false), []);
  useDismissOnFocusOutside(open, fieldRef, dismiss);

  const summary = useMemo(() => {
    if (values.length === 0) return '';
    if (values.length <= 2) return values.join('、');
    return `已选 ${values.length} 项`;
  }, [values]);

  const toggle = (option: string) => {
    if (values.includes(option)) {
      onChange(values.filter((item) => item !== option));
    } else {
      onChange([...values, option]);
    }
  };

  return (
    <div className="cm-multi-field" ref={fieldRef}>
      <button
        type="button"
        className="vm-input cm-multi-trigger"
        onClick={() => setOpen((prev) => !prev)}
        aria-label={ariaLabel}
        aria-expanded={open}
      >
        {summary || <span className="placeholder">{placeholder}</span>}
        <ChevronDown size={14} aria-hidden />
      </button>
      {values.length > 0 && (
        <button
          type="button"
          className="cm-multi-clear"
          onClick={(event) => {
            event.stopPropagation();
            onChange([]);
          }}
          aria-label={`清空${ariaLabel}`}
        >
          <X size={14} aria-hidden />
        </button>
      )}
      {open && (
        <div className="cm-multi-popover" role="listbox" aria-label={ariaLabel}>
          {options.map((option) => (
            <label key={option} className="cm-multi-option">
              <input
                type="checkbox"
                checked={values.includes(option)}
                onChange={() => toggle(option)}
              />
              <span>{option}</span>
            </label>
          ))}
        </div>
      )}
    </div>
  );
}
