import React, { useEffect, useMemo, useState } from 'react';
import { X } from 'lucide-react';
import type { VehicleRecord } from '../types';
import {
  buildOperateCityTree,
  operateCityValueToLocation,
  toOperateCityValue,
} from '../utils/filters';
import { formatOperateCity, parseRegionParts } from '../utils/vehicle';

interface OperateCityEditModalProps {
  open: boolean;
  record: VehicleRecord | null;
  records: VehicleRecord[];
  onClose: () => void;
  onSave: (location: string) => void;
}

export function OperateCityEditModal({
  open,
  record,
  records,
  onClose,
  onSave,
}: OperateCityEditModalProps) {
  const tree = useMemo(() => buildOperateCityTree(records), [records]);
  const [province, setProvince] = useState('');
  const [selected, setSelected] = useState('');

  useEffect(() => {
    if (!open || !record) return;
    const current = formatOperateCity(record.location);
    const { province: currentProvince } = parseRegionParts(current);
    const fallbackProvince = tree.find((node) => node.province === currentProvince)?.province
      || tree[0]?.province
      || '';
    setProvince(currentProvince || fallbackProvince);
    setSelected(current);
  }, [open, record, tree]);

  if (!open || !record) return null;

  const activeProvince = province || tree[0]?.province || '';
  const cityOptions = tree.find((node) => node.province === activeProvince)?.cities ?? [];
  const selectedInProvince = parseRegionParts(selected).province === activeProvince ? selected : '';

  const pickCity = (city: string) => {
    setSelected(toOperateCityValue(activeProvince, city));
  };

  const handleSave = () => {
    if (!selected) return;
    onSave(operateCityValueToLocation(selected));
  };

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div className="vm-modal vm-modal-sm" role="dialog" aria-modal="true" aria-labelledby="vm-operate-city-edit-title" onClick={(e) => e.stopPropagation()}>
        <header className="vm-modal-header">
          <div>
            <h2 id="vm-operate-city-edit-title">修改运营城市</h2>
            <p>{record.plateNo} · 当前 {formatOperateCity(record.location)}</p>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-operate-city-edit-body">
          <label className="vm-operate-city-step vm-operate-city-step-single">
            <span>省份</span>
            <select
              className="vm-input"
              value={activeProvince}
              onChange={(event) => setProvince(event.target.value)}
              aria-label="选择省份"
            >
              {tree.map((node) => (
                <option key={node.province} value={node.province}>{node.province}</option>
              ))}
            </select>
          </label>
          <div className="vm-operate-city-edit-cities" role="listbox" aria-label="城市列表">
            {cityOptions.length === 0 ? (
              <p className="vm-operate-city-empty">暂无可选城市</p>
            ) : (
              cityOptions.map((city) => {
                const full = toOperateCityValue(activeProvince, city);
                const checked = selectedInProvince === full || selected === full;
                return (
                  <button
                    key={full}
                    type="button"
                    role="option"
                    aria-selected={checked}
                    className={`vm-operate-city-edit-option ${checked ? 'checked' : ''}`}
                    onClick={() => pickCity(city)}
                  >
                    {full}
                  </button>
                );
              })
            )}
          </div>
        </div>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-ghost" onClick={onClose}>取消</button>
          <button type="button" className="vm-btn vm-btn-primary" onClick={handleSave} disabled={!selected}>保存</button>
        </footer>
      </div>
    </div>
  );
}
