import React, { useCallback, useEffect, useRef, useState } from 'react';
import ConfirmDialog from './ConfirmDialog';

const SAMPLE_PORTRAIT =
  'data:image/svg+xml,' +
  encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" width="240" height="300" viewBox="0 0 240 300">
      <rect fill="#E8FFEA" width="240" height="300"/>
      <circle cx="120" cy="110" r="50" fill="#C9CDD4"/>
      <ellipse cx="120" cy="240" rx="70" ry="55" fill="#C9CDD4"/>
      <text x="120" y="290" text-anchor="middle" fill="#86909C" font-size="12">示例照片</text>
    </svg>`
  );

export default function CameraCapture({
  photoDataUrl,
  confirmed,
  onCapture,
  onConfirm,
  onRetake,
  cameraPermission,
  showDevFallback,
}) {
  const videoRef = useRef(null);
  const streamRef = useRef(null);
  const [preview, setPreview] = useState(photoDataUrl);
  const [error, setError] = useState('');
  const [permissionDenied, setPermissionDenied] = useState(false);
  const [showPermissionDialog, setShowPermissionDialog] = useState(false);

  const stopStream = useCallback(() => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach((t) => t.stop());
      streamRef.current = null;
    }
  }, []);

  const startCamera = useCallback(async () => {
    if (cameraPermission === 'deny') {
      setPermissionDenied(true);
      setShowPermissionDialog(true);
      return;
    }
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 } },
        audio: false,
      });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
        await videoRef.current.play();
      }
      setError('');
      setPermissionDenied(false);
    } catch {
      setPermissionDenied(true);
      setShowPermissionDialog(true);
    }
  }, [cameraPermission]);

  useEffect(() => {
    if (!preview && !confirmed) startCamera();
    return () => stopStream();
  }, [preview, confirmed, startCamera, stopStream]);

  const handleCapture = () => {
    const video = videoRef.current;
    if (!video) return;
    const canvas = document.createElement('canvas');
    canvas.width = video.videoWidth || 640;
    canvas.height = video.videoHeight || 480;
    const ctx = canvas.getContext('2d');
    ctx.translate(canvas.width, 0);
    ctx.scale(-1, 1);
    ctx.drawImage(video, 0, 0);
    const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
    setPreview(dataUrl);
    stopStream();
    onCapture?.(dataUrl);
  };

  const handleRetake = () => {
    setPreview(null);
    onRetake?.();
    startCamera();
  };

  const handleUseSample = () => {
    setPreview(SAMPLE_PORTRAIT);
    onCapture?.(SAMPLE_PORTRAIT);
  };

  if (confirmed && photoDataUrl) {
    return (
      <div style={{ textAlign: 'center' }}>
        <img src={photoDataUrl} alt="本人照片" className="dt-portrait-preview" />
        <div className="dt-success-banner" style={{ marginTop: 12 }}>
          <span>✓</span>
          <span>本人照片已确认</span>
        </div>
      </div>
    );
  }

  return (
    <div>
      <p className="dt-field-hint" style={{ marginBottom: 12 }}>
        请由司机本人使用前置摄像头拍摄正面照片，用于本次培训和现场交车核验。
      </p>
      <ul className="dt-camera-tips">
        <li>请正对摄像头</li>
        <li>保持光线充足</li>
        <li>请勿佩戴口罩或遮挡面部</li>
      </ul>

      {!preview ? (
        <div className="dt-camera-container">
          <video ref={videoRef} className="dt-camera-video" playsInline muted />
          <div className="dt-camera-guide">
            <div className="dt-camera-oval" />
          </div>
        </div>
      ) : (
        <div style={{ textAlign: 'center' }}>
          <img src={preview} alt="预览" className="dt-portrait-preview" style={{ width: '100%', maxWidth: 280, height: 'auto' }} />
        </div>
      )}

      {error && <div className="dt-field-error">{error}</div>}

      <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
        {!preview ? (
          <button type="button" className="dt-btn-primary" onClick={handleCapture} disabled={permissionDenied}>
            拍摄
          </button>
        ) : (
          <>
            <button type="button" className="dt-btn-outline" onClick={handleRetake}>
              重新拍摄
            </button>
            <button type="button" className="dt-btn-primary" style={{ flex: 1 }} onClick={() => onConfirm?.()}>
              确认使用
            </button>
          </>
        )}
      </div>

      {showDevFallback && permissionDenied && (
        <button type="button" className="dt-btn-secondary" style={{ marginTop: 10 }} onClick={handleUseSample}>
          使用示例照片（开发模式）
        </button>
      )}

      <ConfirmDialog
        visible={showPermissionDialog}
        title="摄像头权限"
        content="无法调用摄像头，请在浏览器设置中允许摄像头权限后重试。"
        cancelText="关闭"
        confirmText="重试"
        onCancel={() => setShowPermissionDialog(false)}
        onConfirm={() => {
          setShowPermissionDialog(false);
          startCamera();
        }}
      />
    </div>
  );
}
