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

interface MultiPlateFilterFieldProps {
  value: string[];
  onChange: (plateNos: string[]) => void;
  placeholder?: string;
  ariaLabel: string;
  hint?: string;
}

export function MultiPlateFilterField({
  value,
  onChange,
  placeholder = '点击输入多个车牌',
  ariaLabel,
  hint = '每行一个车牌，或同一行内用逗号分隔',
}: MultiPlateFilterFieldProps) {
  const [open, setOpen] = useState(false);
  const [draft, setDraft] = useState('');
  const fieldRef = useRef<HTMLDivElement>(null);

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

  useDismissOnFocusOutside(open, fieldRef, dismiss);

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

  const openPopover = () => {
    setDraft(value.join('\n'));
    setOpen(true);
  };

  const handleConfirm = () => {
    onChange(parseMultiPlates(draft));
    setOpen(false);
  };

  return (
    <div className="vm-plate-field" ref={fieldRef}>
      <button
        type="button"
        className="vm-input vm-plate-trigger"
        aria-label={ariaLabel}
        aria-expanded={open}
        onClick={openPopover}
      >
        {summary || <span className="placeholder">{placeholder}</span>}
        <ChevronDown size={14} aria-hidden />
      </button>
      {open && (
        <div className="vm-plate-popover" role="dialog" aria-label={`${ariaLabel} 多选`}>
          {hint ? <div className="vm-plate-popover-hint">{hint}</div> : null}
          <textarea
            className="vm-input vm-plate-textarea"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder={'沪A03561F\n粤B58888F'}
            rows={5}
            aria-label={`${ariaLabel} 输入区`}
          />
          <div className="vm-plate-popover-actions">
            <button type="button" className="vm-btn vm-btn-ghost" onClick={dismiss} data-vm-icon="x">
              取消
            </button>
            <button type="button" className="vm-btn vm-btn-primary" onClick={handleConfirm} data-vm-icon="send">
              确认
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
