/* eslint-disable no-unused-vars */
import { useState, useEffect } from "react";
import { useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom";
import { apiCall, apiCallCasino, authHeader } from "../../config/HTTP";
import { CONST } from "../../config/Const";
import Loader from "../../component/Loader/Loader";
import { toast } from "react-toastify";



const IframeCasinonew = () => {
    const [isFetchingUrl, setIsFetchingUrl] = useState(false);
    const [redirectUrl, setRedirectUrl] = useState("");
    const [isIframe, setIsIframe] = useState(false);
    const location = useLocation();
    const [searchParams] = useSearchParams();
    // Extract query parameters
    const { providerName, gameId } = useParams();
    const gameName = searchParams.get('game_name');
    const id = searchParams.get('id');
    const navigate = useNavigate();
    useEffect(() => {
        test();
    }, [providerName, gameId]);

    useEffect(() => {
        testOne();
    }, [providerName, gameId]);

    const test = async (value) => {
        setIsFetchingUrl(true);
        try {
            if (!authHeader().Authorization) return
            const response = await fetch(`${CONST.CASINO_URL}game-login`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    ...authHeader(),
                },
                body: JSON.stringify({
                    providerName: providerName,
                    gameId: gameId,
                }),
            });

            const result = await response.json();
            if (result?.data?.url) {
                setIsIframe(true);
                setRedirectUrl(result?.data?.url);
            }

            // Check for error case with message "valid token" and show a toast message
            // if (result?.error === true) {
            //     // Show success toast
            //     toast.error("Token is invalid");

            //     // Redirect to Dashboard after showing the toast
            //     navigate("/dashboard");
            // }
        } catch (error) {
            console.error(error);
        } finally {
            setIsFetchingUrl(false);
        }
    };

    const testOne = async (value) => {
        let login = localStorage.getItem('token');
        if (!login) return
        setIsFetchingUrl(true);
        try {
            if (!authHeader().Authorization) return
            const response = await fetch(`${CONST.CASINO_URL}game-login`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    ...authHeader(),
                },

                body: JSON.stringify({
                    providerName: providerName,
                    gameId: gameId,
                }),
            });
            if (!authHeader().Authorization) return
            const result = await response.json();
            if (result?.data?.url) {
                setIsIframe(true);
                setRedirectUrl(result?.data?.url);
            }
            if (result?.error === true) {

                toast.error("Token is invalid");
                localStorage.clear()
                navigate("/dashboard");
            }
        } catch (error) {
            console.error(error);
        } finally {
            setIsFetchingUrl(false);
        }
    };

    return (
        isFetchingUrl ? <Loader /> : <div className="flex">
            <div
                className="h-[calc(100vh-60px)]"
                style={{
                    width: "100%",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    backgroundColor: "#000",
                }}
            >
                {isIframe && (
                    <iframe
                        src={redirectUrl}
                        title="Casino Game"
                        loading="lazy"
                        className="mx-auto w-[100%] h-full"
                    />
                )}
            </div>
            {/* <div className="col-lg-3 score-tabbets ">
                <RightSidebar />
            </div> */}
        </div>
    );
};

export default IframeCasinonew;
