import React, { useEffect } from 'react';
import { Button, Toast } from 'antd-mobile';
import { useCamera } from '../../hooks';
import './index.css';

interface CameraCaptureProps {
  onCapture: (file: File) => void;
  onClose?: () => void;
}

const CameraCapture: React.FC<CameraCaptureProps> = ({ onCapture, onClose }) => {
  const { videoRef, canvasRef, isReady, error, start, stop, capture } = useCamera();
  
  useEffect(() => {
    start();
    
    return () => {
      stop();
    };
  }, [start, stop]);
  
  const handleCapture = async () => {
    const file = await capture();
    if (file) {
      onCapture(file);
    } else {
      Toast.show({ content: '拍照失败', icon: 'fail' });
    }
  };
  
  if (error) {
    return (
      <div className="camera-error">
        <p>{error}</p>
        <Button onClick={start}>重试</Button>
      </div>
    );
  }
  
  return (
    <div className="camera-capture">
      <video 
        ref={videoRef} 
        className="camera-video"
        playsInline
        autoPlay
      />
      <canvas ref={canvasRef} className="camera-canvas" />
      
      <div className="camera-controls">
        <Button 
          className="capture-btn"
          onClick={handleCapture}
          disabled={!isReady}
        >
          拍照
        </Button>
        
        {onClose && (
          <Button onClick={onClose}>取消</Button>
        )}
      </div>
    </div>
  );
};

export default CameraCapture;