import { useRef, useEffect, useState, useCallback } from "react";
import WithModal from "@/Components/WithModal";

const CameraModal = ({ isOpen, onClose, onCapture, id = 'camera_modal' }) => {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const [stream, setStream] = useState(null);
  const [error, setError] = useState(null);

  const startCamera = async () => {
    try {
      setError(null);
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: "environment" },
        audio: false,
      });
      setStream(mediaStream);
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream;
      }
    } catch (err) {
      console.error("Error accessing camera:", err);
      setError("Gagal mengakses kamera. Pastikan izin kamera diberikan.");
    }
  };

  const stopCamera = useCallback(() => {
    if (stream) {
      stream.getTracks().forEach((track) => track.stop());
      setStream(null);
    }
  }, [stream]);

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

  const handleCapture = () => {
    if (videoRef.current && canvasRef.current) {
      const video = videoRef.current;
      const canvas = canvasRef.current;
      const context = canvas.getContext("2d");

      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      context.drawImage(video, 0, 0, canvas.width, canvas.height);

      canvas.toBlob((blob) => {
        const file = new File([blob], `capture_${Date.now()}.png`, { type: "image/png" });
        onCapture(file);
        onClose();
      }, "image/png");
    }
  };

  const handleClose = () => {
    stopCamera();
    onClose();
  };

  return (
    <WithModal type={id} backdrop onClick={handleClose} modalBoxSize="max-w-lg" boxClassName="modal-box p-0">
      <div className="w-full">
        <div className="relative w-full h-[400px] flex items-center justify-center bg-black">
          {error ? (
            <div className="text-error text-center p-4">{error}</div>
          ) : (
            <video
              ref={videoRef}
              autoPlay
              playsInline
              className="w-full h-full object-cover"
            />
          )}
        </div>

        <div className="p-4 bg-base-100 flex justify-center">
          {!error && (
            <button
              className="btn btn-circle btn-outline btn-primary btn-lg border-4"
              onClick={handleCapture}
              aria-label="Capture Photo"
            >
              <div className="w-12 h-12 bg-primary rounded-full border-2 border-white"></div>
            </button>
          )}
        </div>

        <canvas ref={canvasRef} className="hidden" />
      </div>
    </WithModal>
  );
};

export default CameraModal;
