import React, {
    useRef,
    useEffect,
    forwardRef,
    useImperativeHandle,
} from "react";
import videojs from "video.js";
import "video.js/dist/video-js.css";

const VideoPlayer = function VideoPlayer({
    videoRef,
    playerInstanceRef,
    setMarkerTimeFunc,
    authenticatedFetch
}) {
    useEffect(() => {
        // Prevent double init in StrictMode
        if (!playerInstanceRef.current && videoRef.current) {
            const token = localStorage.getItem("access_token"); // Move token here

            playerInstanceRef.current = videojs(videoRef.current, {
                controls: true,
                preload: "auto",
                autoplay: true,
                fill: true,
                html5: {
                    vhs: {
                        overrideNative: true,  // use Video.js native range handling
                    },
                    nativeVideoTracks: false,
                },
                techOrder: ['html5'],
            })

            playerInstanceRef.current.on("timeupdate", async function (event) {
                const token = localStorage.getItem("access_token");
                const res = await authenticatedFetch("api/events/video_step", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ timestamp: this.currentTime() }),
                });

                if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
                let js_ = await res.json()

                const { path, timeoffset, do_update, absolute_time, halt } = js_
                setMarkerTimeFunc(1000 * absolute_time);
                if (halt) {
                    this.pause();
                }
                if (do_update) {
                    const authenticatedUrl = `api/${path}?token=${token}`;
                    console.log(authenticatedUrl)
                    playerInstanceRef.current.src({
                        src: authenticatedUrl,
                        type: "video/mp4",
                    });

                    // Seek after metadata is loaded
                    playerInstanceRef.current.on("loadedmetadata", () => {
                        playerInstanceRef.current.currentTime(timeoffset);
                    });
                }
            });
        }

        return () => {
            if (playerInstanceRef.current) {
                playerInstanceRef.current.dispose();
                playerInstanceRef.current = null;
            }
        };
    }, []);

    return (
        <div style={{ width: "100%", height: "100%" }}>
            <div data-vjs-player style={{ width: "100%", height: "100%" }}>
                <video
                    ref={videoRef}
                    className="video-js vjs-big-play-centered"
                    playsInline
                    style={{
                        width: "100%",
                        height: "100%",
                        backgroundColor: "black",
                        objectFit: "contain",
                    }}
                />
            </div>
        </div>
    );
};

export default VideoPlayer;
