"use client";

import { useRef, useEffect, useState } from "react";

interface WebcamCaptureProps {
  onFrameCapture: (blob: Blob) => void;
  captureInterval?: number;
  isActive: boolean;
  videoRef?: React.RefObject<HTMLVideoElement | null>;
}

export default function WebcamCapture({
  onFrameCapture,
  captureInterval = 500,
  isActive,
  videoRef: externalVideoRef,
}: WebcamCaptureProps) {
  const internalVideoRef = useRef<HTMLVideoElement>(null);
  const videoRef = externalVideoRef || internalVideoRef;
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [error, setError] = useState<string>("");

  useEffect(() => {
    // Start webcam
    const startWebcam = async () => {
      try {
        const mediaStream = await navigator.mediaDevices.getUserMedia({
          video: { width: 640, height: 480 },
          audio: false,
        });

        if (videoRef.current) {
          videoRef.current.srcObject = mediaStream;
        }

        setStream(mediaStream);
        setError("");
      } catch (err) {
        setError("Failed to access webcam. Please grant camera permissions.");
        console.error("Error accessing webcam:", err);
      }
    };

    startWebcam();

    // Cleanup
    return () => {
      if (stream) {
        stream.getTracks().forEach((track) => track.stop());
      }
    };
  }, []);

  useEffect(() => {
    if (!isActive || !videoRef.current || !canvasRef.current) return;

    const interval = setInterval(() => {
      captureFrame();
    }, captureInterval);

    return () => clearInterval(interval);
  }, [isActive, captureInterval]);

  const captureFrame = () => {
    const video = videoRef.current;
    const canvas = canvasRef.current;

    if (!video || !canvas || video.readyState !== video.HAVE_ENOUGH_DATA) {
      return;
    }

    const context = canvas.getContext("2d");
    if (!context) return;

    // Set canvas size to match video
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    // Draw current video frame to canvas
    context.drawImage(video, 0, 0, canvas.width, canvas.height);

    // Convert canvas to blob and pass to parent
    canvas.toBlob(
      (blob) => {
        if (blob) {
          onFrameCapture(blob);
        }
      },
      "image/jpeg",
      0.8
    );
  };

  return (
    <>
      {error && (
        <div className="absolute top-0 left-0 right-0 bg-red-500 text-white p-2 text-center z-20">
          {error}
        </div>
      )}
      <video
        ref={videoRef}
        autoPlay
        playsInline
        className="w-full h-auto rounded-lg shadow-lg border-4 border-purple-500"
        style={{ transform: "scaleX(-1)" }}
      />
      <canvas ref={canvasRef} className="hidden" />
    </>
  );
}
