import { useEffect, useRef, useState } from "react";
import shaka from "shaka-player";
import { toast } from "sonner";
import Container from "../Container";
import NavBar from "../NavBar";

function TestPlayer() {
    const [mpdUrl, setMpdUrl] = useState("");
    const [headers, setHeaders] = useState("");
    const [keyPairs, setKeyPairs] = useState(""); // "kid:key" per line

    const videoRef = useRef(null);
    const playerRef = useRef(null);

    const handleInputChange = (event) => {
        setMpdUrl(event.target.value);
    };

    const handleKeyPairsChange = (event) => {
        setKeyPairs(event.target.value);
    };

    const handleHeadersChange = (event) => {
        setHeaders(event.target.value);
    };

    // Function to initialize Shaka Player
    const initializePlayer = async () => {
        if (videoRef.current && !playerRef.current) {
            const player = new shaka.Player(); // no mediaElement
            await player.attach(videoRef.current); // attach later
            playerRef.current = player;

            player.addEventListener("error", (event) => {
                toast.error(`Error code ${event.detail.code}: ${event.detail.message}`);
                console.error("Error code", event.detail.code, "object", event.detail);
            });
        }
    };

    // Function to handle submit and configure player with DRM keys and headers
    const handleSubmit = () => {
        if (mpdUrl && keyPairs) {
            // Parse KID:KEY pairs
            const lines = keyPairs
                .split("\n")
                .map((line) => line.trim())
                .filter(Boolean);
            const clearKeys = {};

            for (const line of lines) {
                const [kid, key] = line.split(":").map((part) => part.trim());
                if (!kid || !key) {
                    toast.error(`Invalid line (expected format keyId:key) at line "${line}"`);
                    console.error(`Invalid line (expected format keyId:key) at line "${line}"`);
                    return;
                }
                clearKeys[kid] = key;
            }

            // Initialize Shaka Player only when the submit button is pressed
            const player = new shaka.Player(videoRef.current);

            // Widevine DRM configuration with the provided KIDs and Keys
            const config = {
                drm: {
                    clearKeys: clearKeys,
                },
            };

            console.log("Configuring player with the following DRM config and headers:", config);

            // Configure the player with ClearKey DRM and custom headers
            player.configure(config);

            // Load the video stream with MPD URL
            player
                .load(mpdUrl)
                .then(() => {
                    console.log("Video loaded");
                    toast.success("Video successfully loaded");
                })
                .catch((error) => {
                    toast.error(`Error loading the video. Reason: ${error.message}`);
                    console.error("Error loading the video", error);
                });
        } else {
            toast.error("Manifest URL and key pairs are required");
            console.error("Manifest URL and key pairs are required.");
        }
    };

    // Load the video stream whenever the MPD URL changes
    useEffect(() => {
        initializePlayer(); // Initialize the player if it's not initialized already
    }, []); // This effect runs only once on mount

    // Helper function to parse headers from the textarea input
    const parseHeaders = (headersText) => {
        const headersArr = headersText.split("\n");
        const headersObj = {};
        headersArr.forEach((line) => {
            const [key, value] = line.split(":");
            if (key && value) {
                headersObj[key.trim()] = value.trim();
            }
        });
        return headersObj;
    };

    useEffect(() => {
        document.title = "Test player | CDRM-Project";
    }, []);

    return (
        <>
            <NavBar />
            <Container>
                <div className="flex w-full flex-col items-center justify-center py-8">
                    <div className="flex w-full flex-col items-center lg:flex-row lg:items-start lg:gap-4">
                        {/* Video Section */}
                        <div className="w-full lg:w-1/2">
                            <video
                                ref={videoRef}
                                width="100%"
                                height="auto"
                                controls
                                className="aspect-video max-h-96 w-full"
                            />
                        </div>

                        {/* Inputs Section */}
                        <div className="mt-4 flex w-full flex-col items-center lg:mt-0 lg:w-1/2">
                            <fieldset className="fieldset w-full">
                                <legend className="fieldset-legend text-base">Manifest URL*</legend>
                                <input
                                    type="text"
                                    value={mpdUrl}
                                    onChange={handleInputChange}
                                    placeholder="Enter manifest URL here"
                                    className="input w-full font-mono"
                                />
                                <p className="label text-red-500">* Required</p>
                            </fieldset>
                            <fieldset className="fieldset w-full">
                                <legend className="fieldset-legend text-base">Key pairs*</legend>
                                <textarea
                                    placeholder="keyId:key pair (one per line)"
                                    value={keyPairs}
                                    onChange={handleKeyPairsChange}
                                    className="textarea w-full font-mono"
                                />
                                <p className="label text-red-500">* Required</p>
                            </fieldset>
                            <fieldset className="fieldset w-full">
                                <legend className="fieldset-legend text-base">Headers</legend>
                                <textarea
                                    placeholder="Headers (one per line)"
                                    value={headers}
                                    onChange={handleHeadersChange}
                                    className="textarea w-full font-mono"
                                />
                            </fieldset>
                            <button
                                onClick={handleSubmit}
                                className="btn btn-primary btn-wide my-4"
                            >
                                Submit
                            </button>
                        </div>
                    </div>
                </div>
            </Container>
        </>
    );
}

export default TestPlayer;
