import React, { useRef, useState } from 'react';
import CertificateUploadCard from '../components/CertificateUploadCard';
import { ManualCertificateForm, getCertFieldLabel } from '../components/OCRResultForm';
import UploadSourceSheet from '../components/UploadSourceSheet';
import { CERT_TYPES, OCR_MOCK } from '../data/constants';
import { isQualificationRequired, getRequiredCertTypes } from '../context/TrainingContext';

const OCR_CERT_TYPES = [CERT_TYPES.ID_FRONT, CERT_TYPES.LICENSE_FRONT, CERT_TYPES.QUALIFICATION];
const BACK_ONLY = [CERT_TYPES.ID_BACK, CERT_TYPES.LICENSE_BACK];

function parseValidEnd(period) {
  if (!period) return null;
  const parts = period.split(/[—\-~]/);
  const end = parts[parts.length - 1]?.trim().replace(/\./g, '-');
  return end ? new Date(end) : null;
}

export default function Step3Certificates({ state, updateCertificate, completeStep, renderPart = 'all' }) {
  const tonnage = state.trainingTask.vehicleTonnage;
  const requiredTypes = getRequiredCertTypes(tonnage);
  const showOptionalQual = !isQualificationRequired(tonnage);
  const certs = state.step3.certificates;
  const requiredDoneCount = requiredTypes.filter((t) => certs[t]?.status === 'done').length;
  const allDone = requiredDoneCount === requiredTypes.length;
  const cameraRef = useRef(null);
  const albumRef = useRef(null);
  const [uploadSheetCert, setUploadSheetCert] = useState(null);
  const [activeCert, setActiveCert] = useState(null);
  const [modal, setModal] = useState(null);
  const [formData, setFormData] = useState({});
  const [formErrors, setFormErrors] = useState({});
  const [validationError, setValidationError] = useState('');
  const ocrMode = state.debug.ocrMode;

  const allCertTypes = showOptionalQual
    ? [...requiredTypes, CERT_TYPES.QUALIFICATION]
    : requiredTypes;

  const showUploadOptions = (certType) => {
    setUploadSheetCert(certType);
  };

  const pickCamera = () => {
    if (!uploadSheetCert) return;
    setActiveCert(uploadSheetCert);
    setUploadSheetCert(null);
    setTimeout(() => cameraRef.current?.click(), 0);
  };

  const pickAlbum = () => {
    if (!uploadSheetCert) return;
    setActiveCert(uploadSheetCert);
    setUploadSheetCert(null);
    setTimeout(() => albumRef.current?.click(), 0);
  };

  const runOCR = (certType, imageUrl) => {
    updateCertificate(certType, { status: 'recognizing', imageUrl });
    setTimeout(() => {
      if (ocrMode === 'fail') {
        updateCertificate(certType, { status: 'failed', imageUrl, mode: 'ocr' });
        setModal({ type: 'ocr_fail', certType, imageUrl });
        return;
      }
      let mock = { ...OCR_MOCK[certType] };
      if (ocrMode === 'mismatch' && certType === CERT_TYPES.LICENSE_FRONT) {
        mock = { ...mock, name: '李晓明', licenseNumber: '3304**********9999' };
      }
      updateCertificate(certType, { status: 'confirm', imageUrl, mode: 'ocr', fields: mock, ocrData: mock });
      setModal({ type: 'confirm', certType, imageUrl, fields: mock });
      setFormData(mock);
    }, 1000);
  };

  const handleFile = (e) => {
    const file = e.target.files?.[0];
    if (!file || !activeCert) return;
    const reader = new FileReader();
    updateCertificate(activeCert, { status: 'uploading' });
    reader.onload = () => {
      if (BACK_ONLY.includes(activeCert)) {
        setTimeout(() => {
          updateCertificate(activeCert, {
            status: 'done',
            imageUrl: reader.result,
            fields: OCR_MOCK[activeCert] || {},
            completedAt: new Date().toISOString(),
          });
        }, 800);
      } else {
        runOCR(activeCert, reader.result);
      }
    };
    reader.readAsDataURL(file);
    e.target.value = '';
  };

  const openCert = (certType) => {
    const cert = certs[certType];
    if (cert?.status === 'done') {
      setModal({ type: 'view', certType, ...cert });
      setFormData(cert.fields || {});
      return;
    }
    if (cert?.status === 'confirm') {
      setModal({ type: 'confirm', certType, imageUrl: cert.imageUrl, fields: cert.fields });
      setFormData(cert.fields || {});
      return;
    }
    if (cert?.status === 'failed') {
      setModal({ type: 'ocr_fail', certType, imageUrl: cert.imageUrl });
      return;
    }
    showUploadOptions(certType);
  };

  const confirmCert = () => {
    const { certType } = modal;
    const errors = {};
    const fields = formData;
    if (OCR_CERT_TYPES.includes(certType)) {
      if (!fields.name) errors.name = '请填写姓名';
      if (certType === CERT_TYPES.ID_FRONT && !fields.idNumber) errors.idNumber = '请填写身份证号';
      if (certType === CERT_TYPES.LICENSE_FRONT) {
        if (!fields.licenseNumber) errors.licenseNumber = '请填写证号';
        if (!fields.vehicleClass) errors.vehicleClass = '请选择准驾车型';
        if (!fields.validPeriod) errors.validPeriod = '请填写有效期限';
      }
      if (certType === CERT_TYPES.QUALIFICATION) {
        if (!fields.certNumber) errors.certNumber = '请填写证号';
        if (!fields.vehicleClass) errors.vehicleClass = '请填写准驾车型';
        if (!fields.category) errors.category = '请填写从业资格类别';
        if (!fields.initialIssueDate) errors.initialIssueDate = '请填写初次领证日期';
        if (!fields.validFrom) errors.validFrom = '请填写有效起始日期';
        if (!fields.validPeriod) errors.validPeriod = '请填写有效期限';
      }
    }
    setFormErrors(errors);
    if (Object.keys(errors).length) return;

    updateCertificate(certType, {
      status: 'done',
      fields,
      imageUrl: modal.imageUrl || certs[certType]?.imageUrl,
      mode: modal.mode || certs[certType]?.mode || 'ocr',
      completedAt: new Date().toISOString(),
    });
    setModal(null);
    setFormErrors({});
  };

  const startManual = () => {
    const { certType, imageUrl } = modal;
    updateCertificate(certType, { status: 'confirm', mode: 'manual', imageUrl, fields: {} });
    setModal({ type: 'manual', certType, imageUrl, mode: 'manual' });
    setFormData({});
  };

  const validateAll = () => {
    const idFront = certs[CERT_TYPES.ID_FRONT]?.fields;
    const license = certs[CERT_TYPES.LICENSE_FRONT]?.fields;

    for (const t of requiredTypes) {
      if (!certs[t] || certs[t].status !== 'done') {
        setValidationError('请完成所有必填证照上传');
        return false;
      }
    }
    if (!idFront || !license) {
      setValidationError('请完成身份证和驾驶证信息确认');
      return false;
    }
    if (idFront.name !== license.name) {
      setValidationError('身份证姓名与驾驶证姓名不一致');
      return false;
    }
    if (idFront.idNumber !== license.licenseNumber) {
      setValidationError('身份证号码与驾驶证证号不一致');
      return false;
    }
    const endDate = parseValidEnd(license.validPeriod);
    if (endDate && endDate < new Date()) {
      setValidationError('驾驶证已过期，请更新证件');
      return false;
    }
    if (license.vehicleClass !== state.trainingTask.requiredVehicleClass) {
      setValidationError(`准驾车型不满足要求，当前车辆需要 ${state.trainingTask.requiredVehicleClass} 驾照`);
      return false;
    }
    setValidationError('');
    return true;
  };

  const modals = (
    <>
      <UploadSourceSheet
        visible={!!uploadSheetCert}
        certType={uploadSheetCert}
        onCamera={pickCamera}
        onAlbum={pickAlbum}
        onCancel={() => setUploadSheetCert(null)}
      />
      {modal?.type === 'ocr_fail' && (
        <div className="dt-modal-overlay" onClick={() => setModal(null)}>
          <div className="dt-modal" onClick={(e) => e.stopPropagation()}>
            <div className="dt-error-card" style={{ margin: 0 }}>
              <p>证件信息识别失败，可以重新拍摄或手动填写。</p>
              <div className="dt-error-actions">
                <button
                  type="button"
                  className="dt-btn-outline"
                  onClick={() => {
                    setModal(null);
                    showUploadOptions(modal.certType);
                  }}
                >
                  重新上传
                </button>
                <button type="button" className="dt-btn-primary" style={{ flex: 1 }} onClick={startManual}>
                  手动填写
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
      {(modal?.type === 'confirm' || modal?.type === 'manual' || modal?.type === 'view') && (
        <div className="dt-modal-overlay" onClick={() => setModal(null)}>
          <div className="dt-modal" onClick={(e) => e.stopPropagation()} style={{ maxHeight: '80vh', overflow: 'auto' }}>
            <h3 className="dt-modal-title">
              {modal.type === 'view' ? '查看证照' : modal.type === 'manual' ? '手动填写' : '确认识别结果'}
            </h3>
            {modal.imageUrl && <img src={modal.imageUrl} alt="" style={{ width: '100%', borderRadius: 8, marginBottom: 12 }} />}
            {(modal.type === 'confirm' || modal.type === 'manual') && OCR_CERT_TYPES.includes(modal.certType) && (
              <ManualCertificateForm
                certType={modal.certType}
                data={formData}
                onChange={(key, val) => setFormData((d) => ({ ...d, [key]: val }))}
                errors={formErrors}
              />
            )}
            {modal.type === 'view' && modal.fields && Object.keys(modal.fields).length > 0 && (
              <div className="dt-info-list">
                {Object.entries(modal.fields)
                  .filter(([k]) => k !== 'fileNumber')
                  .map(([k, v]) => (
                  <div className="dt-info-item" key={k}>
                    <span className="label">{getCertFieldLabel(k)}</span>
                    <span>{v}</span>
                  </div>
                ))}
              </div>
            )}
            <div className="dt-modal-actions" style={{ marginTop: 16 }}>
              <button type="button" className="dt-btn-secondary" onClick={() => setModal(null)}>关闭</button>
              {modal.type !== 'view' && (
                <button type="button" className="dt-btn-primary" onClick={confirmCert}>确认</button>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );

  const content = (
    <>
      <input
        ref={cameraRef}
        type="file"
        accept="image/*"
        capture="environment"
        style={{ display: 'none' }}
        onChange={handleFile}
      />
      <input
        ref={albumRef}
        type="file"
        accept="image/*"
        style={{ display: 'none' }}
        onChange={handleFile}
      />
      <div className="dt-card">
        <h2 className="dt-card-title">司机证照</h2>
        <p className="dt-field-hint" style={{ marginBottom: 12 }}>
          {isQualificationRequired(tonnage)
            ? `当前车辆为 ${tonnage} 吨，从业资格证为必填项。`
            : `当前车辆为 ${tonnage} 吨，从业资格证为选填项。`}
          点击证件卡片可选择拍照或从相册上传。
        </p>
        {allCertTypes.map((t) => (
          <CertificateUploadCard
            key={t}
            certType={t}
            required={requiredTypes.includes(t)}
            status={certs[t]?.status || 'pending'}
            imageUrl={certs[t]?.imageUrl}
            onClick={() => openCert(t)}
          />
        ))}
        {allDone && (
          <div className="dt-success-banner">
            <span>✓</span>
            <span>证照信息已完成</span>
          </div>
        )}
        {validationError && <div className="dt-field-error" style={{ marginTop: 8 }}>{validationError}</div>}
      </div>
      {modals}
    </>
  );

  const footer = (
    <>
      {!allDone && (
        <div className="dt-footer-hint">
          请完成全部必填证照上传（{requiredDoneCount}/{requiredTypes.length}）
        </div>
      )}
      <button type="button" className="dt-btn-primary" disabled={!allDone} onClick={() => validateAll() && completeStep(3)}>
        下一步
      </button>
    </>
  );

  if (renderPart === 'content') return content;
  if (renderPart === 'footer') return footer;
  return (
    <>
      {content}
      {footer}
    </>
  );
}
