import { useRef, useState, useEffect } from 'react';
import { ocrAPI } from '../services/api';

function Camera({ onCapture, onClose }) {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const fileInputRef = useRef(null);
  const [stream, setStream] = useState(null);
  const [captured, setCaptured] = useState(null);
  const [parsing, setParsing] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    startCamera();
    return () => stopCamera();
  }, []);

  useEffect(() => {
    if (stream && videoRef.current) {
      videoRef.current.srcObject = stream;
      videoRef.current.onloadedmetadata = () => {
        videoRef.current.play().catch(() => {});
      };
      videoRef.current.play().catch(() => {});
    }
  }, [stream]);

  const startCamera = async () => {
    try {
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: 'environment', width: 1280, height: 720 }
      });
      setStream(mediaStream);
    } catch (err) {
      setError('无法访问摄像头，请检查权限或使用上传功能');
    }
  };

  const stopCamera = () => {
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
    }
  };

  const capture = () => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (!video || !canvas) return;

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0);

    canvas.toBlob(blob => {
      setCaptured(blob);
      stopCamera();
    }, 'image/jpeg', 0.9);
  };

  const handleFileSelect = (e) => {
    const file = e.target.files[0];
    if (file) {
      setCaptured(file);
      stopCamera();
    }
  };

  const retake = () => {
    setCaptured(null);
    setError('');
    startCamera();
  };

  const parseImage = async () => {
    if (!captured) return;

    setParsing(true);
    setError('');

    try {
      const { data } = await ocrAPI.parse(captured);
      onCapture(data);
    } catch (err) {
      setError(err.response?.data?.error || '识别失败，请重试或手动输入');
    } finally {
      setParsing(false);
    }
  };

  return (
    <div className="camera-fullscreen">
      {error && <div className="camera-error">{error}</div>}

      <div className="camera-preview">
        {!captured ? (
          <video ref={videoRef} autoPlay playsInline muted />
        ) : (
          <img src={URL.createObjectURL(captured)} alt="captured" />
        )}
      </div>

      <canvas ref={canvasRef} style={{display: 'none'}} />
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        style={{display: 'none'}}
      />

      <div className="camera-controls">
        {!captured ? (
          <>
            <button className="btn btn-primary" onClick={capture}>拍照</button>
            <button className="btn btn-secondary" onClick={() => fileInputRef.current?.click()}>
              上传图片
            </button>
            <button className="btn btn-secondary" onClick={onClose}>取消</button>
          </>
        ) : (
          <>
            <button className="btn btn-primary" onClick={parseImage} disabled={parsing}>
              {parsing ? '识别中...' : '开始识别'}
            </button>
            <button className="btn btn-secondary" onClick={retake} disabled={parsing}>重拍</button>
            <button className="btn btn-secondary" onClick={onClose} disabled={parsing}>取消</button>
          </>
        )}
      </div>
    </div>
  );
}

export default Camera;
