import React, { useEffect } from 'react'
import { Box, Container } from '@mui/material'
import Webcam from 'react-webcam'
import axios from 'axios'

const WebcamComponent: React.FC = () => {
  const webcamRef = React.useRef<Webcam>(null)
  const canvasRef = React.useRef<HTMLCanvasElement>(null)

  useEffect(() => {
    const intervalId = setInterval(() => {
      if (webcamRef.current?.video && canvasRef.current) {
        const video = webcamRef.current.video
        const frame = webcamRef.current.getScreenshot()
        // Get Video Properties
        const videoWidth = webcamRef.current.video.videoWidth
        const videoHeight = webcamRef.current.video.videoHeight

        // Set video width
        webcamRef.current.video.width = videoWidth
        webcamRef.current.video.height = videoHeight

        // Set canvas height and width

        const canvas = canvasRef.current
        canvas.width = videoWidth
        canvas.height = videoHeight
        const context = canvas.getContext('2d')

        if (frame && context) {
          axios
            .post(
              'http://127.0.0.1:5000/predict',
              { frame },
              {
                headers: {
                  'Content-Type': 'application/json',
                  charset: 'utf-8',
                },
              },
            )
            .then((response) => {
              console.log(response)

              // Draw the prediction and rectangle on the canvas
              canvas.width = video.videoWidth
              canvas.height = video.videoHeight
              context.drawImage(video, 0, 0, canvas.width, canvas.height)
              context.font = '18px Arial'
              if (response.data.status) {
                context.fillStyle = 'green'
                context.strokeStyle = 'green'
              } else {
                context.fillStyle = 'red'
                context.strokeStyle = 'red'
              }
              context.fillText(`Prediction: ${response.data.prediction}`, 50, 45)
              context.lineWidth = 2
              context.strokeRect(50, 50, 180, 180)
            })
            .catch((error) => {
              console.error('Error:', error)
            })
        }
      }
    }, 1000) // Adjust the interval as needed

    return () => clearInterval(intervalId)
  }, [])

  return (
    <Container maxWidth='sm'>
      <Box
        sx={{
          position: 'relative',
          width: 640,
          height: 480,
        }}
      >
        <Webcam
          ref={webcamRef}
          muted={true}
          style={{
            position: 'absolute',
            width: '100%',
            height: '100%',
          }}
        />

        <canvas
          ref={canvasRef}
          style={{
            position: 'absolute',
            width: '100%',
            height: '100%',
          }}
        />
      </Box>
    </Container>
  )
}

export default WebcamComponent
