"use client";
import { Category, GameListRep, getGameDetailApi } from "@/api/home";
import Box from "@/components/Box";
import { useRouter } from "@/i18n/routing";
import { useWalletStore } from "@/stores/useWalletStore";
import { brandList } from "@/utils/constant";
import { getToken } from "@/utils/Cookies";
import { Button, Popup, Toast } from "antd-mobile";
import { useTranslations } from "next-intl";
import { FC, PropsWithChildren, ReactNode, useRef, useState } from "react";
import styles from "./style.module.scss";
export interface CardProps {
    item?: GameListRep;
    render?: (value: GameListRep) => ReactNode;
    groupType?: Category["bet_type"];
}

const whiteUrls = ["192.168.0.84", "localhost", "192.168.0.46"];
const Card: FC<PropsWithChildren<CardProps>> = (props) => {
    const { render, item, groupType } = props;

    const t = useTranslations("Game");
    const tcode = useTranslations();
    const brandRef = useRef<string>("");
    const wallet = useWalletStore((state) => state.wallet);

    const [visible, setVisible] = useState(false);

    const router = useRouter();
    const token = getToken();
    const handler = (game: GameListRep) => {
        setVisible(true);
        brandRef.current = brandList.find((item) => item.gid === game.game_id)?.brand ?? "";
    };
    const playGameHandler = (game: GameListRep) => {
        if (!token) {
            router.push("/login?redirect=/");
            return;
        }
        if (groupType === 1 && Number(wallet.score) <= 0) {
            router.push("/deposit");
            return;
        }
        Toast.show({
            icon: "loading",
            duration: 0,
            maskStyle: { zIndex: 99999, background: "rgba(0,0,0,0.5)" },
        });
        const params = {
            id: game.id + "",
            mode: groupType!,
        };
        getGameDetailApi(params)
            .then((res) => {
                Toast.clear();
                if (res.data && res.data.game_url) {
                    const url = `${res.data?.game_url}&brand=${brandRef.current}&return_url=${process.env.NEXT_PUBLIC_SHARE_URL}`;
                    const protocol = new URL(url).protocol;
                    if (
                        whiteUrls.indexOf(window.location.hostname) !== -1 ||
                        protocol === "https:"
                    ) {
                        router.push(`/game?${url}`);
                    } else {
                        window.open(url);
                    }
                } else {
                    Toast.show(tcode("code.500"));
                }
            })
            .catch((error) => {
                Toast.clear();
            });
    };
    return (
        <>
            {render ? (
                render(item!)
            ) : (
                <div className={styles.cardWrap} onClick={() => handler(item!)}>
                    <img
                        src={item?.game_icon}
                        alt={item?.game_name_cn}
                        className={"h-[100%] w-[100%]"}
                    />
                </div>
            )}

            <Popup
                visible={visible}
                onMaskClick={() => {
                    setVisible(false);
                }}
                onClose={() => {
                    setVisible(false);
                }}
                showCloseButton={true}
                getContainer={() => document.querySelector("#app")!}
                bodyStyle={{ background: "#1c1c1c" }}
            >
                <Box className={"w-1/1 flex w-[4.02rem] flex-1"}>
                    <div className={styles.cardWrap} style={{ width: "1.1rem" }}>
                        <img
                            src={item?.game_icon}
                            alt={item?.game_name_cn}
                            className={"h-[100%] w-[100%]"}
                        />
                    </div>
                    <div className={styles.cardWrapGmeInfo}>
                        <p className={"h-[0.6rem]"}>{item?.game_name_cn}</p>

                        <div className={"flex w-[2.2rem] justify-around"}>
                            {/*<Button*/}
                            {/*    onClick={playGameHandler}*/}
                            {/*    className={*/}
                            {/*        "h-[0.39rem] w-[0.89rem] rounded-[0.05rem] text-[0.15rem]" +*/}
                            {/*        " bg-[#3a3a3a]" +*/}
                            {/*        " font-bold"*/}
                            {/*    }*/}
                            {/*>*/}
                            {/*    {t("demo")}*/}
                            {/*</Button>*/}
                            <Button
                                onClick={() => playGameHandler(item!)}
                                style={{
                                    "--background-color": "#009d80",
                                    "--border-color": "#009d80",
                                }}
                                className={`h-[0.39rem] w-[0.89rem] rounded-[0.05rem] bg-[#] text-[0.15rem] font-bold`}
                            >
                                {t("join")}
                            </Button>
                        </div>
                    </div>
                </Box>
            </Popup>
        </>
    );
};

export default Card;
