import React, { useEffect, useRef, useState } from 'react';

import { formatNow } from '../utils/formatDateTime';

import SignatureCanvas from '../components/SignatureCanvas';
import ConfirmDialog from '../components/ConfirmDialog';

function useContainerLandscape(rootRef) {
  const [isLandscape, setIsLandscape] = useState(false);

  useEffect(() => {
    const root = rootRef.current?.closest('.driver-training-app') || rootRef.current;
    if (!root) return undefined;

    const check = () => {
      const { width, height } = root.getBoundingClientRect();
      setIsLandscape(width > height * 1.05);
    };

    check();
    const observer = new ResizeObserver(check);
    observer.observe(root);
    window.addEventListener('orientationchange', check);
    return () => {
      observer.disconnect();
      window.removeEventListener('orientationchange', check);
    };
  }, [rootRef]);

  return isLandscape;
}

export default function Step7Signature({
  state,
  updateState,
  submitTraining,
  goToStep,
  renderPart = 'all',
}) {
  const { step6, step3, trainingTask } = state;
  const [showSubmitDialog, setShowSubmitDialog] = useState(false);
  const rootRef = useRef(null);
  const canvasRef = useRef(null);
  const isLandscape = useContainerLandscape(rootRef);
  const hasSignature = !!step6.signatureDataUrl;

  const driverName = step3.certificates?.idFront?.fields?.name || '—';

  const handleSubmit = () => {
    submitTraining();
    setShowSubmitDialog(false);
  };

  if (step6.submitted) {
    if (renderPart === 'footer') return null;
    return (
      <div className="dt-card">
        <div className="dt-success-banner">
          <span>✓</span>
          <span>培训记录已提交</span>
        </div>
      </div>
    );
  }

  if (renderPart === 'footer') return null;

  const dialogSummary = (
    <>
      <div className="dt-modal-summary-row">
        <span className="label">司机</span>
        <span>{driverName}</span>
      </div>
      <div className="dt-modal-summary-row">
        <span className="label">车辆</span>
        <span>{trainingTask.vehiclePlate}</span>
      </div>
      <div className="dt-modal-summary-row">
        <span className="label">培训完成时间</span>
        <span>{formatNow()}</span>
      </div>
      {hasSignature && (
        <div className="dt-modal-signature-preview">
          <span className="label">签名预览</span>
          <img src={step6.signatureDataUrl} alt="签名预览" />
        </div>
      )}
    </>
  );

  const submitDialog = (
    <ConfirmDialog
      visible={showSubmitDialog}
      title="确认提交培训并生成提车码"
      note="提交后不可修改，提车码将出示给运维扫码。"
      summary={dialogSummary}
      cancelText="返回检查"
      confirmText="确认提交"
      onCancel={() => setShowSubmitDialog(false)}
      onConfirm={handleSubmit}
    />
  );

  return (
    <div
      ref={rootRef}
      className={`dt-esign-root ${isLandscape ? 'dt-esign-root--landscape' : 'dt-esign-root--portrait-preview'}`}
    >
      {!isLandscape && (
        <div className="dt-esign-preview-banner">
          <div className="dt-esign-preview-banner-icon" aria-hidden="true">
            ↻
          </div>
          <div className="dt-esign-preview-banner-text">
            <strong>横屏签字预览</strong>
            <span>正式使用时请旋转手机至横屏；下方为横屏全屏签名页效果，可直接体验签字并完成提交。</span>
          </div>
        </div>
      )}

      <div className="dt-esign-landscape">
        <header className="dt-esign-topbar">
          <button type="button" className="dt-esign-topbar-back" onClick={() => goToStep(6)} aria-label="返回">
            ‹
          </button>
          <h1 className="dt-esign-topbar-title">手写签名</h1>
          <span className="dt-esign-topbar-slot" />
        </header>

        <div className="dt-esign-signer">
          <span>{driverName}</span>
          <span className="dt-esign-signer-dot">·</span>
          <span>{trainingTask.vehiclePlate}</span>
        </div>

        <div className="dt-esign-canvas-area">
          <SignatureCanvas
            ref={canvasRef}
            variant="esign"
            hideActions
            watermark="请在此处签名"
            value={step6.signatureDataUrl}
            onChange={(url) =>
              updateState((prev) => ({ ...prev, step6: { ...prev.step6, signatureDataUrl: url } }))
            }
          />
        </div>

        <footer className="dt-esign-toolbar">
          <button type="button" className="dt-esign-tool-btn" onClick={() => canvasRef.current?.clear()}>
            清除重写
          </button>
          <button type="button" className="dt-esign-tool-btn" onClick={() => goToStep(6)}>
            取消
          </button>
          <button
            type="button"
            className={`dt-esign-tool-done ${hasSignature ? 'dt-esign-tool-done--ready' : ''}`}
            disabled={!hasSignature}
            onClick={() => setShowSubmitDialog(true)}
          >
            完成
          </button>
        </footer>
      </div>
      {submitDialog}
    </div>
  );
}
