import { CameraSharp } from "@mui/icons-material";
import { Button, IconButton } from "@mui/material";
import Image from "next/image";
import React, { useRef } from "react";
import Webcam from "react-webcam";

interface WebcamCaptureProps {
  image: string | null;
  setImage: (image: string | null) => void;
  isWebcamVisible: boolean;
  setIsWebcamVisible: (isVisible: boolean) => void;
}

const WebcamCapture: React.FC<WebcamCaptureProps> = ({
  image,
  setImage,
  isWebcamVisible,
  setIsWebcamVisible,
}) => {
  const webcamRef = useRef<Webcam>(null);

  // Mengambil foto dari webcam
  const capture = () => {
    const image = webcamRef.current?.getScreenshot();
    setIsWebcamVisible(false);
    setImage(image || null);
  };

  const takePicture = () => {
    setImage(null);
    setIsWebcamVisible(true);
  };

  // Mengatur ukuran webcam
  const videoConstraints = {
    width: 500,
    height: 480,
    facingMode:  {
      exact: "environment" // untuk kamera belakang
    },
  };

  return (
    <div className="items-center">
      {!isWebcamVisible && (
        <Button variant="text" size="large" onClick={() => takePicture()}>
          Ambil Foto Surat Jalan
        </Button>
      )}
    
      {isWebcamVisible && (
        <div>
          <Webcam
            audio={false}
            ref={webcamRef}
            screenshotFormat="image/jpeg"
            videoConstraints={videoConstraints}
          />
          <IconButton aria-label="camera" size="large" onClick={() => capture()}>
            <CameraSharp fontSize="inherit" />
          </IconButton>
        </div>
      )}
      {image && (
        <div>
          <Image
            src={image}
            alt="Captured"
            width={500}
            height={480}
            unoptimized 
          />
        </div>
      )}
    </div>
  );
};

export default WebcamCapture;
