import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Search, X } from 'lucide-react';
import {
  buildChinaOperateCityTree,
  flattenOperateCityOptions,
  formatOperateCityChipLabel,
  matchOperateCityOption,
  operateCityValueToLocation,
  toOperateCityValue,
  type OperateCityOption,
} from '../utils/filters';
import { formatOperateCity, parseRegionParts } from '../utils/vehicle';

interface OperateCityPickerPanelProps {
  location: string;
  onSelect: (location: string) => void;
  autoFocusSearch?: boolean;
}

export function OperateCityPickerPanel({
  location,
  onSelect,
  autoFocusSearch = false,
}: OperateCityPickerPanelProps) {
  const tree = useMemo(() => buildChinaOperateCityTree(), []);
  const allOptions = useMemo(() => flattenOperateCityOptions(tree), [tree]);
  const [province, setProvince] = useState('');
  const [selected, setSelected] = useState('');
  const [query, setQuery] = useState('');
  const searchRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const formatted = formatOperateCity(location);
    const { province: locProvince } = parseRegionParts(formatted);
    const fallback = tree.find((node) => node.province === locProvince)?.province
      || tree[0]?.province
      || '';
    setProvince(locProvince || fallback);
    setSelected(formatted);
    setQuery('');
    if (autoFocusSearch) {
      window.requestAnimationFrame(() => searchRef.current?.focus());
    }
  }, [location, tree, autoFocusSearch]);

  const activeProvince = province || tree[0]?.province || '';
  const searchText = query.trim();
  const isSearchMode = searchText.length > 0;

  const displayOptions: OperateCityOption[] = useMemo(() => {
    if (isSearchMode) {
      return allOptions.filter((option) => matchOperateCityOption(option, searchText));
    }
    const node = tree.find((item) => item.province === activeProvince);
    if (!node) return [];
    return node.cities.map((city) => {
      const value = toOperateCityValue(activeProvince, city);
      return {
        value,
        label: formatOperateCityChipLabel(value),
        province: activeProvince,
      };
    });
  }, [isSearchMode, searchText, allOptions, tree, activeProvince]);

  const pickOption = (option: OperateCityOption) => {
    setSelected(option.value);
    setProvince(option.province);
    onSelect(operateCityValueToLocation(option.value));
  };

  const handleProvinceChange = (nextProvince: string) => {
    setProvince(nextProvince);
    setQuery('');
    const { province: selectedProvince } = parseRegionParts(selected);
    if (selectedProvince && selectedProvince !== nextProvince) {
      setSelected('');
    }
  };

  const clearSearch = () => {
    setQuery('');
    searchRef.current?.focus();
  };

  const selectedLabel = selected ? formatOperateCityChipLabel(selected) : '';

  return (
    <div className="vm-operate-city-edit-body vm-operate-city-picker-panel">
      <label className="vm-operate-city-edit-search">
        <Search size={16} aria-hidden className="vm-operate-city-edit-search-icon" />
        <input
          ref={searchRef}
          type="text"
          className="vm-operate-city-edit-search-input"
          value={query}
          placeholder="输入省份或城市名称快速筛选"
          aria-label="搜索省份或城市"
          autoComplete="off"
          onChange={(event) => setQuery(event.target.value)}
        />
        {query ? (
          <button
            type="button"
            className="vm-operate-city-edit-search-clear"
            onClick={clearSearch}
            aria-label="清空搜索"
          >
            <X size={14} aria-hidden />
          </button>
        ) : null}
      </label>

      {selected ? (
        <div className="vm-operate-city-edit-selected" aria-live="polite">
          <span className="vm-operate-city-edit-selected-label">已选</span>
          <span className="vm-operate-city-edit-selected-value">{selectedLabel}</span>
        </div>
      ) : null}

      <div className={`vm-operate-city-edit-main${isSearchMode ? ' is-search' : ''}`}>
        {!isSearchMode && (
          <div className="vm-operate-city-edit-step vm-operate-city-edit-step--province">
            <span className="vm-operate-city-step-label">省份</span>
            <div className="vm-operate-city-edit-chips" role="tablist" aria-label="省份快捷选择">
              {tree.map((node) => {
                const active = activeProvince === node.province;
                return (
                  <button
                    key={node.province}
                    type="button"
                    role="tab"
                    aria-selected={active}
                    className={`vm-operate-city-chip${active ? ' active' : ''}`}
                    onClick={() => handleProvinceChange(node.province)}
                  >
                    {node.province}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        <div className="vm-operate-city-edit-step vm-operate-city-edit-step--city">
          <span className="vm-operate-city-step-label">
            {isSearchMode ? `搜索结果（${displayOptions.length}）` : '城市'}
          </span>
          <div className="vm-operate-city-edit-chips" role="listbox" aria-label="城市列表">
            {displayOptions.length === 0 ? (
              <p className="vm-operate-city-empty">
                {isSearchMode ? '未找到匹配的城市，请换个关键词' : '暂无可选城市'}
              </p>
            ) : (
              displayOptions.map((option) => {
                const checked = selected === option.value;
                return (
                  <button
                    key={option.value}
                    type="button"
                    role="option"
                    aria-selected={checked}
                    className={`vm-operate-city-chip${checked ? ' active' : ''}`}
                    onClick={() => pickOption(option)}
                  >
                    {option.label}
                  </button>
                );
              })
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
