"use client";

import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import videojs from "video.js";
import "videojs-contrib-quality-levels";
import "video.js/dist/video-js.css";
import * as Sentry from "@sentry/browser";

import { attachKeyAuth } from "@/components/video/hls/key-auth";
import QualityMenu from "@/components/video/hls/quality-menu";
import Watermark from "@/components/video/hls/watermark";
import { PlaybackHooks } from "@/components/video/playback";

type Player = ReturnType<typeof videojs>;

interface VideoPlayerHLSProps {
    src: string;
    /** Rangook's encrypted HLS: send the Bearer token with key requests (technical-plan 6.6). */
    keyAuth?: boolean;
    /** The viewer's masked mobile, moved around over the video. */
    watermark?: string | null;
    poster?: string | null;
    /** Starting bandwidth estimate for adaptive bitrate; ~1.5 Mbit/s starts at 480p. */
    startBandwidth?: number;
    /** Resume, progress and seeking for the page (Rangook lessons). */
    playback?: PlaybackHooks;
}

export default function VideoPlayerHLS({ src, keyAuth = false, watermark = null, poster = null, startBandwidth, playback }: VideoPlayerHLSProps) {
    const videoRef = useRef<HTMLDivElement | null>(null);
    // The listeners are attached once; they read the page's latest hooks from here.
    const playbackRef = useRef<PlaybackHooks | undefined>(playback);
    useEffect(() => {
        playbackRef.current = playback;
    });
    const playerRef = useRef<any>(null);
    // The player element hosts the quality menu and watermark (portals), so they stay in fullscreen.
    const [player, setPlayer] = useState<Player | null>(null);

    const retryCountRef = useRef(0);
    const retryDelays = [2000, 5000, 10000];

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

        if (!playerRef.current) {
            const videoElement = document.createElement("video-js");

            videoElement.classList.add(
                "video-js",
                "vjs-big-play-centered",
                "vjs-fluid",
                "w-full"
            );

            videoElement.style.width = "100%";
            videoElement.style.height = "100%";

            videoRef.current.appendChild(videoElement);

            const player = (playerRef.current = videojs(videoElement, {
                controls: true,
                responsive: true,
                fluid: false,
                preload: "auto",
                poster: poster ?? undefined,
                html5: {
                    // VHS everywhere MSE exists, so the key hook below also runs on Android WebView.
                    // Start at 480p (technical-plan 6.6), then adapt to measured downloads:
                    // - useDevicePixelRatio: renditions are capped by the player's size in device
                    //   pixels, not CSS pixels, so a phone (DPR 2-3) isn't held at 360p;
                    // - useNetworkInformationApi off: otherwise the browser's coarse
                    //   navigator.connection.downlink replaces the starting estimate below.
                    vhs: {
                        overrideNative: true,
                        useDevicePixelRatio: true,
                        useNetworkInformationApi: false,
                        ...(startBandwidth ? { bandwidth: startBandwidth } : {}),
                    },
                    nativeAudioTracks: false,
                    nativeVideoTracks: false,
                },
            }));

            if (keyAuth) {
                attachKeyAuth(player);
            }

            player.src({ src: src, type: "application/x-mpegURL" });
            player.ready(() => setPlayer(player));

            /*
            -------------------------
            PLAYBACK HOOKS (resume, progress, seek)
            -------------------------
            */

            const startAt = playbackRef.current?.startAt ?? 0;
            if (startAt > 0) {
                player.one("loadedmetadata", () => player.currentTime(startAt));
            }

            const now = () => Number(player.currentTime()) || 0;
            player.on("timeupdate", () => playbackRef.current?.onTime?.(now()));
            player.on("pause", () => playbackRef.current?.onPause?.(now()));
            player.on("ended", () => playbackRef.current?.onEnded?.(now()));
            player.ready(() => playbackRef.current?.onReady?.({
                seek(seconds: number) {
                    player.currentTime(seconds);
                    player.play()?.catch(() => { });
                },
            }));

            /*
            -------------------------
            QUALITY FIX
            -------------------------
            */

            const levels = (player as any).qualityLevels();

            levels.on("addqualitylevel", (event: any) => {
                const level = event.qualityLevel;

                if (level.width < level.height) {
                    level.width = level.height;
                }
            });

            /*
            -------------------------
            SUCCESS RESET
            -------------------------
            */

            player.on("playing", () => {
                retryCountRef.current = 0;
            });

            /*
            -------------------------
            NETWORK OFFLINE
            -------------------------
            */

            window.addEventListener("offline", () => {
                player.createModal("اتصال اینترنت قطع شده است", {
                    temporary: true,
                    pauseOnOpen: false,
                });
            });

            /*
            -------------------------
            ERROR HANDLER
            -------------------------
            */

            player.on("error", () => {
                const error = player.error();

                const retryCount = retryCountRef.current;

                Sentry.captureException(new Error("Video Player Error"), {
                    tags: {
                        component: "video-player",
                    },
                    extra: {
                        src: src,
                        code: error?.code,
                        message: error?.message,
                        retryCount: retryCount,
                    },
                });

                const errorDisplay = player.getChild("errorDisplay");

                if (errorDisplay) {
                    const el = errorDisplay.contentEl();
                    if (el) {
                        el.innerHTML = "مشکلی در پخش ویدیو پیش آمد (" + retryCount + ")";
                    }
                }

                if (retryCount < retryDelays.length) {
                    const delay = retryDelays[retryCount];
                    retryCountRef.current++;

                    setTimeout(() => {
                        player.src({
                            src: src,
                            type: "application/x-mpegURL",
                        });

                        player.load();
                        player.play()?.then(() => { }).catch(() => { });
                    }, delay);
                } else {
                    if (errorDisplay) {
                        const el = errorDisplay.contentEl();
                        if (el) {
                            el.innerHTML =
                                "پخش ویدیو با مشکل مواجه شد. لطفاً صفحه را رفرش کنید.";
                        }
                    }
                }
            });

            /*
            -------------------------
            QUALITY ANALYTICS
            -------------------------
            */

            player.on("qualitychange", () => {
                const levels = (player as any).qualityLevels();

                for (let i = 0; i < levels.length; i++) {
                    const level = levels[i];

                    if (level.enabled) {
                        console.log("quality changed:", level.height);

                        Sentry.addBreadcrumb({
                            category: "video-quality",
                            message: `${level.height}p`,
                            level: "info",
                        });
                    }
                }
            });
        } else {
            const player = playerRef.current;

            player.src({
                src: src,
                type: "application/x-mpegURL",
            });
        }

        return () => {
            if (playerRef.current && !playerRef.current.isDisposed()) {
                playerRef.current.dispose();
                playerRef.current = null;
                setPlayer(null);
            }
        };
    }, [src]);

    return (
        // w-full: as a flex item with mx-auto it would otherwise shrink to its absolutely
        // positioned content, i.e. zero width and height (inherited from Gymobi).
        <div className="w-full max-w-4xl mx-auto" dir="ltr">
            <div
                data-vjs-player
                className="w-full relative pt-[56.25%]"
                dir="ltr"
            >
                <div ref={videoRef} className="absolute inset-0" />
            </div>

            {player && !player.isDisposed() && createPortal(<QualityMenu player={player} />, player.el())}
            {player && !player.isDisposed() && watermark && createPortal(<Watermark text={watermark} />, player.el())}
        </div>
    );
}