import React, { useMemo, useState } from 'react';
import { X } from 'lucide-react';
import type { VehicleRecord } from '../types';
import { resolveOpsStaffCandidates, resolveVehicleRegion } from '../utils/vehicle';
import { OpsManagerMultiSelect } from './OpsManagerMultiSelect';

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

export function OpsManagerModal({ open, record, onClose, onSave }: OpsManagerModalProps) {
  const [selected, setSelected] = useState<string[]>([]);

  React.useEffect(() => {
    if (open && record) {
      setSelected(record.opsManagers || []);
    }
  }, [open, record]);

  const candidates = useMemo(
    () => (record ? resolveOpsStaffCandidates(record) : []),
    [record],
  );

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

  const regionLabel = resolveVehicleRegion(record);

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div className="vm-modal vm-modal-sm" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
        <header className="vm-modal-header">
          <div>
            <h2>设置运维负责人</h2>
            <div className="vm-ops-vehicle-capsule" aria-label={`${record.plateNo} ${regionLabel}`}>
              <span className="vm-ops-vehicle-plate">{record.plateNo}</span>
              <span className="vm-ops-vehicle-divider" aria-hidden />
              <span className="vm-ops-vehicle-region">{regionLabel}</span>
            </div>
          </div>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-ops-body">
          <OpsManagerMultiSelect
            value={selected}
            options={candidates}
            onChange={setSelected}
          />
        </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={() => onSave(selected)}>保存</button>
        </footer>
      </div>
    </div>
  );
}
