import React, { useCallback, useMemo, useRef, useState } from 'react';
import { ChevronDown, X } from 'lucide-react';
import type { VehicleRecord } from '../types';
import { buildOperateCityTree, toOperateCityValue } from '../utils/filters';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';

interface OperateCityFieldProps {
  records: VehicleRecord[];
  value: string[];
  onChange: (cities: string[]) => void;
}

export function OperateCityField({ records, value, onChange }: OperateCityFieldProps) {
  const tree = useMemo(() => buildOperateCityTree(records), [records]);
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(false);
  const [province, setProvince] = useState('');
  const [query, setQuery] = useState('');
  const fieldRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

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

  useDismissOnFocusOutside(open, fieldRef, dismiss);

  const activeProvince = province || tree[0]?.province || '';

  const summary = value.length <= 2
    ? value.join('、')
    : value.length > 0
      ? `已选 ${value.length} 个城市`
      : '';

  const flatCities = useMemo(
    () => tree.flatMap((node) => node.cities.map((city) => toOperateCityValue(node.province, city))),
    [tree],
  );

  const cityOptions = useMemo(() => {
    const q = query.trim();
    if (q) return flatCities.filter((item) => item.includes(q));
    const node = tree.find((n) => n.province === activeProvince);
    if (!node) return [];
    return node.cities.map((city) => toOperateCityValue(activeProvince, city));
  }, [query, tree, activeProvince, flatCities]);

  const toggleCity = (full: string) => {
    if (value.includes(full)) {
      onChange(value.filter((v) => v !== full));
    } else {
      onChange([...value, full]);
    }
  };

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

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

  return (
    <div className="vm-operate-city-field" ref={fieldRef}>
      <div className={`vm-filter-picker-control ${open ? 'open' : ''}`}>
        <input
          ref={inputRef}
          type="text"
          className="vm-filter-picker-input"
          value={editing ? query : summary}
          placeholder="请选择省-市"
          aria-label="运营城市"
          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.length > 0 ? (
          <button
            type="button"
            className="vm-filter-picker-clear"
            onClick={clearAll}
            aria-label="清空运营城市"
            tabIndex={-1}
          >
            <X size={14} aria-hidden />
          </button>
        ) : null}
        <ChevronDown size={14} className="vm-filter-picker-chevron" aria-hidden />
      </div>

      {open && (
        <div className="vm-operate-city-popover" role="dialog" aria-label="运营城市选择">
          {!query.trim() && (
            <label className="vm-operate-city-step vm-operate-city-step-single">
              <span>省份</span>
              <select
                className="vm-input"
                value={activeProvince}
                onChange={(e) => {
                  setProvince(e.target.value);
                }}
                aria-label="选择省份"
              >
                {tree.map((node) => (
                  <option key={node.province} value={node.province}>{node.province}</option>
                ))}
              </select>
            </label>
          )}

          <div className="vm-operate-city-options" role="listbox" aria-label="城市列表" aria-multiselectable="true">
            {cityOptions.length === 0 ? (
              <p className="vm-operate-city-empty">暂无匹配城市</p>
            ) : (
              cityOptions.map((full) => {
                const checked = value.includes(full);
                return (
                  <label
                    key={full}
                    className={`vm-operate-city-option ${checked ? 'checked' : ''}`}
                    onMouseDown={(event) => event.preventDefault()}
                  >
                    <input
                      type="checkbox"
                      checked={checked}
                      onChange={() => toggleCity(full)}
                    />
                    <span>{full}</span>
                  </label>
                );
              })
            )}
          </div>

          {value.length > 0 && (
            <div className="vm-operate-city-tags">
              {value.map((city) => (
                <span key={city} className="vm-operate-city-tag">
                  {city}
                  <button
                    type="button"
                    aria-label={`移除${city}`}
                    onMouseDown={(event) => event.preventDefault()}
                    onClick={() => onChange(value.filter((v) => v !== city))}
                  >
                    <X size={12} aria-hidden />
                  </button>
                </span>
              ))}
            </div>
          )}

          <div className="vm-operate-city-actions">
            <button type="button" className="vm-btn vm-btn-primary" onClick={dismiss}>确认</button>
          </div>
        </div>
      )}
    </div>
  );
}
