import React, { useEffect, useMemo, useState } from 'react';
import { X } from 'lucide-react';
import type { VehicleRecord } from '../types';
import { buildOptions } from '../utils/filters';
import {
  OPERATE_STATUS_OPTIONS,
  VEHICLE_SOURCE_OPTIONS,
  VEHICLE_STATUS_OPTIONS,
  applyVehicleEditForm,
  buildYearOptions,
  createVehicleEditForm,
  displayText,
  type VehicleEditForm,
} from '../utils/vehicle';
import { FilterPickerField } from './FilterPickerField';

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

function FormField({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <label className="vm-filter-field vm-form-field">
      <span>{label}</span>
      {children}
    </label>
  );
}

export function VehicleEditModal({
  open,
  record,
  records,
  onClose,
  onSave,
}: VehicleEditModalProps) {
  const [form, setForm] = useState<VehicleEditForm>(createVehicleEditForm({} as VehicleRecord));
  const parkings = useMemo(() => buildOptions(records, 'parking'), [records]);
  const operateCompanies = useMemo(() => buildOptions(records, 'operateCompany'), [records]);
  const ownerships = useMemo(() => buildOptions(records, 'ownership'), [records]);
  const leaseCompanies = useMemo(() => buildOptions(records, 'leaseCompany'), [records]);
  const yearOptions = useMemo(() => buildYearOptions(), []);

  useEffect(() => {
    if (open && record) {
      setForm(createVehicleEditForm(record));
    }
  }, [open, record]);

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

  const update = <K extends keyof VehicleEditForm>(key: K, value: VehicleEditForm[K]) => {
    setForm((prev) => ({ ...prev, [key]: value }));
  };

  const handleSave = () => {
    if (!form.operateStatus || !form.vehicleStatus) return;
    onSave(applyVehicleEditForm(record, form));
  };

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal vm-modal-lg"
        role="dialog"
        aria-modal="true"
        aria-labelledby="vm-edit-vehicle-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="vm-modal-header">
          <div>
            <h2 id="vm-edit-vehicle-title">编辑车辆信息</h2>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-edit-body">
          <div className="vm-edit-banner">
            车牌号：<strong>{displayText(record.plateNo)}</strong>
            {'　'}识别代码：<span>{displayText(record.vin)}</span>
          </div>
          <div className="vm-form-grid">
            <FormField label="车辆归属停车场">
              <FilterPickerField
                value={form.parking}
                options={parkings}
                placeholder="请选择或输入停车场"
                ariaLabel="车辆归属停车场"
                onChange={(value) => update('parking', value)}
              />
            </FormField>
            <FormField label="运营状态">
              <FilterPickerField
                value={form.operateStatus}
                options={OPERATE_STATUS_OPTIONS}
                placeholder="请选择运营状态"
                ariaLabel="运营状态"
                onChange={(value) => update('operateStatus', value)}
              />
            </FormField>
            <FormField label="车辆状态">
              <FilterPickerField
                value={form.vehicleStatus}
                options={VEHICLE_STATUS_OPTIONS}
                placeholder="请选择车辆状态"
                ariaLabel="车辆状态"
                onChange={(value) => update('vehicleStatus', value)}
              />
            </FormField>
            <FormField label="登记所有权">
              <FilterPickerField
                value={form.ownership}
                options={ownerships}
                placeholder="请选择登记所有权"
                ariaLabel="登记所有权"
                onChange={(value) => update('ownership', value)}
              />
            </FormField>
            <FormField label="运营公司">
              <FilterPickerField
                value={form.operateCompany}
                options={operateCompanies}
                placeholder="请选择运营公司"
                ariaLabel="运营公司"
                onChange={(value) => update('operateCompany', value)}
              />
            </FormField>
            <FormField label="车辆来源">
              <FilterPickerField
                value={form.vehicleSource}
                options={VEHICLE_SOURCE_OPTIONS}
                placeholder="请选择车辆来源"
                ariaLabel="车辆来源"
                onChange={(value) => update('vehicleSource', value)}
              />
            </FormField>
            <FormField label="租赁公司">
              <FilterPickerField
                value={form.leaseCompany}
                options={leaseCompanies}
                placeholder="请选择或搜索租赁公司"
                ariaLabel="租赁公司"
                onChange={(value) => update('leaseCompany', value)}
              />
            </FormField>
            <FormField label="出厂年份">
              <FilterPickerField
                value={form.year}
                options={yearOptions}
                placeholder="请选择出厂年份"
                ariaLabel="出厂年份"
                onChange={(value) => update('year', value)}
              />
            </FormField>
            <FormField label="采购入库时间">
              <input
                className="vm-input vm-form-input"
                value={form.purchaseDate}
                onChange={(e) => update('purchaseDate', e.target.value)}
                placeholder="请输入采购入库时间"
              />
            </FormField>
          </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={!form.operateStatus || !form.vehicleStatus}
          >
            保存
          </button>
        </footer>
      </div>
    </div>
  );
}
