import React, { useState } from 'react';
import { Modal, Form, Input, Upload, Image, Message } from '@arco-design/web-react';
import type { VehicleRecord } from '@/types/vehicle';

type Props = {
  visible: boolean;
  vehicle: VehicleRecord | null;
  onCancel: () => void;
  onOk: (vin: string, plateNo: string) => void;
};

export default function VehiclePlateModal({ visible, vehicle, onCancel, onOk }: Props) {
  const [ocrLoading, setOcrLoading] = useState(false);
  const [licenseImageUrl, setLicenseImageUrl] = useState<string>('');
  const [form] = Form.useForm();

  const handleUploadChange = (fileList: { file?: File; url?: string }[]) => {
    const file = fileList[0]?.file;
    if (!file) return;
    const url = URL.createObjectURL(file);
    setLicenseImageUrl(url);
    setOcrLoading(true);
    // 模拟 OCR 识别，实际对接 OCR 接口
    setTimeout(() => {
      form.setFieldsValue({ vin: vehicle?.vin ?? '', plateNo: vehicle?.plateNo ?? '' });
      setOcrLoading(false);
    }, 1500);
  };

  const handleOk = () => {
    form.validate().then((values) => {
      const v = (values.vin ?? '').trim();
      const p = (values.plateNo ?? '').trim();
      if (!v || !p) {
        Message.warning('请填写车辆识别代号与车牌号');
        return;
      }
      if (vehicle && v !== vehicle.vin) {
        Message.error('车辆识别代号与该车辆不匹配');
        return;
      }
      onOk(v, p);
      reset();
    }).catch(() => {});
  };

  const reset = () => {
    setLicenseImageUrl('');
    setOcrLoading(false);
    form.resetFields();
  };

  const handleCancel = () => {
    reset();
    onCancel();
  };

  return (
    <>
      <Modal
        title="确认上牌信息"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
        style={{ width: 720 }}
        unmountOnExit
        afterClose={reset}
      >
        <div style={{ display: 'flex', gap: 24, minHeight: 280 }}>
          <div style={{ flex: '0 0 320px' }}>
            <div style={{ marginBottom: 8, color: 'var(--color-text-2)' }}>行驶证照片</div>
            {licenseImageUrl ? (
              <Image
                width={320}
                height={200}
                src={licenseImageUrl}
                style={{ objectFit: 'contain', background: 'var(--color-fill-2)', borderRadius: 4 }}
              />
            ) : (
              <Upload
                accept="image/*"
                listType="picture-card"
                limit={1}
                onChange={handleUploadChange}
                customRequest={(option) => {
                  const { file } = option;
                  if (file) handleUploadChange([{ file: file as File }]);
                }}
              >
                <div style={{ padding: 20, textAlign: 'center' }}>上传行驶证照片</div>
              </Upload>
            )}
          </div>
          <div style={{ flex: 1 }}>
            {ocrLoading ? (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 200 }}>
                <span style={{ color: 'var(--color-text-2)' }}>识别中，请勿关闭页面</span>
              </div>
            ) : (
              <Form form={form} layout="vertical" initialValues={{ vin: vehicle?.vin ?? '', plateNo: vehicle?.plateNo ?? '' }}>
                <Form.Item label="车辆识别代号（VIN）" field="vin" rules={[{ required: true, message: '请填写车辆识别代号' }]}>
                  <Input placeholder="根据行驶证照片反写，可编辑" />
                </Form.Item>
                <Form.Item label="车牌号" field="plateNo" rules={[{ required: true, message: '请填写车牌号' }]}>
                  <Input placeholder="根据行驶证照片反写，可编辑" />
                </Form.Item>
              </Form>
            )}
          </div>
        </div>
      </Modal>
    </>
  );
}
