"use client";
import { Category, GameListRep, GameRequest, toggleFavorite } from "@/api/home";
import { userInfoApi } from "@/api/login";
import useGame from "@/hooks/useGame";
import { useRouter } from "@/i18n/routing";
import { useWalletStore } from "@/stores/useWalletStore";
import { getToken } from "@/utils/Cookies";
import { Button, Image, Popup, Toast } from "antd-mobile";
import clsx from "clsx";
import { useTranslations } from "next-intl";
import { FC, PropsWithChildren, ReactNode, useEffect, useRef, useState } from "react";
import { shallow } from "zustand/shallow";
import TipsModal, { ModalProps } from "../TipsModal";
import styles from "./style.module.scss";

export interface CardProps {
    item?: GameListRep;
    render?: (value: GameListRep) => ReactNode;
    groupType?: Category["bet_type"];
    isShowOnline?: boolean;
    isShowFavorite?: boolean;
    className?: string;
}

const Card: FC<PropsWithChildren<CardProps>> = (props) => {
    const { render, item, groupType, className } = props;

    const { getGameUrl, getCoinType } = useGame();
    const t = useTranslations("Game");
    const brandRef = useRef<GameListRep | null>(null);
    const [isFavorite, setIsFavorite] = useState(item?.is_favorite === 1 || false);
    const wallet = useWalletStore((state) => {
        return {
            score: state.wallet?.score,
            point: state.wallet?.point,
            free_score: state.wallet?.free_score,
            lose_score: state.wallet?.lose_score,
        };
    }, shallow);
    // 判断是否有未结算的对局
    const gameModelRef = useRef<ModalProps>(null);
    const gameRef = useRef<(GameListRep & { mode: GameRequest["mode"] }) | null>(null);

    const [visible, setVisible] = useState(false);
    const element = useRef<HTMLElement | null>(null);

    const router = useRouter();
    const token = getToken();
    const handler = (game: GameListRep) => {
        setVisible(true);
        brandRef.current = game;
    };
    useEffect(() => {
        element.current = document.getElementById("app");
    }, []);
    const playGameHandler = async (game: GameListRep) => {
        const type = getCoinType(game, groupType!);

        if (!token) {
            router.push("/login?redirect=/");
            return;
        }
        // 现金游戏
        if (type === 1 && Number(wallet.score) + wallet.point <= 0) {
            router.push("/deposit");
            return;
        }

        // 免费游戏
        if (type === 2 && Number(wallet.free_score) <= 0) {
            // router.push("/deposit");
            Toast.show({
                icon: "fail",
                content: "No free coins",
                maskClickable: false,
            });
            return;
        }
        // 重玩游戏
        if (type === 3 && Number(wallet.lose_score) <= 0) {
            Toast.show({
                icon: "fail",
                content: "No replay coins",
                maskClickable: false,
            });
            return;
        }

        let params: any = {
            id: game.id + "",
            mode: type!,
        };
        // 判断是否有未结算的游戏
        const { data }: any = await userInfoApi();
        const play_list = data?.play_list.map((item: any) => {
            return {
                ...item,
                mode: 1,
            };
        });
        const free_game_list = data?.free_game_list.map((item: any) => {
            return {
                ...item,
                mode: 2,
            };
        });
        const lose_game_list = data?.lose_game_list.map((item: any) => {
            return {
                ...item,
                mode: 3,
            };
        });
        let gameList = [...free_game_list, ...lose_game_list];
        if (type === 2) {
            gameList = [...play_list, ...lose_game_list];
        }
        if (type === 3) {
            gameList = [...play_list, ...free_game_list];
        }
        let unfinishedGame = gameList.find((item: { id: number }) => item?.id === game.id);
        if (unfinishedGame) {
            gameRef.current = unfinishedGame;
            setVisible(false);
            gameModelRef.current?.onOpen();
            return;
        }
        getGameUrl(brandRef.current!, params);
    };

    const goGame = () => {
        getGameUrl(gameRef.current!, {
            id: gameRef.current?.id + "",
            mode: gameRef.current?.mode!,
        });
    };

    const demoPlayGameHandler = (game: GameListRep) => {
        const params = {
            id: game.id + "",
            demo: game.demo,
        };
        getGameUrl(game, params);
    };

    const doFavorite = async (evt: React.MouseEvent) => {
        evt.stopPropagation();
        if (!getToken) {
            router.push("/login");
        }
        if (!item?.id) return;
        const params = {
            game_id: item?.id,
        };
        let res = null;
        res = await toggleFavorite(params);
        if (res.code === 200) {
            setIsFavorite(!isFavorite);
            // Toast.show({
            //     icon: "success",
            //     content: isFavorite ? "Cancelar favoritos com sucesso" : "Sucesso na coleção",
            //     maskClickable: false,
            // });
        }
    };

    return (
        <>
            {render ? (
                render(item!)
            ) : (
                <div
                    className={clsx(styles.cardWrap, className, "overflow-hidden")}
                    onClick={() => handler(item!)}
                >
                    <Image
                        lazy={true}
                        src={item?.game_icon}
                        alt={item?.game_name_cn}
                        width={"100%"}
                        height={"1.54rem"}
                        className={"h-[100%] w-[100%]"}
                    />
                    {props.isShowOnline && item?.online_user && (
                        <div className={styles.cardOnline}>{item?.online_user} On-Line</div>
                    )}
                    {props.isShowFavorite && (
                        <div
                            className={clsx(styles.favorite, { [styles.active]: isFavorite })}
                            onClick={doFavorite}
                        >
                            {isFavorite && (
                                <i className="iconfont icon-ertong21 text-[#f6cf1e]"></i>
                            )}
                            {!isFavorite && <i className="iconfont icon-ertong"></i>}
                        </div>
                    )}
                </div>
            )}

            <Popup
                visible={visible}
                onMaskClick={() => {
                    setVisible(false);
                }}
                onClose={() => {
                    setVisible(false);
                }}
                style={{ "--adm-color-weak": "#fff" } as any}
                showCloseButton={true}
                getContainer={() => document.querySelector("#app")!}
                bodyStyle={{
                    background: "#1f2830",
                    // borderRadius: ".1rem .1rem 0 0",
                    // border: "1px solid #e53fff",
                    // boxShadow: "0rem -.06rem 20px 0.0rem #e53fff inset",
                    padding: ".06rem .02rem",
                }}
            >
                <div className={"w-1/1 flex w-[4.02rem] flex-1 px-spacing-x py-spacing-y"}>
                    <div className={styles.cardWrap} style={{ width: "1.1rem" }}>
                        <Image
                            src={item?.game_icon}
                            alt={item?.game_name + "-" + item?.category_name}
                            className={"h-[100%] w-[100%]"}
                            height={"1.54rem"}
                        />
                    </div>
                    <div className={styles.cardWrapGmeInfo}>
                        <p className={"h-[0.6rem] text-[.18rem]"}>{item?.game_name}</p>

                        <div className={"flex w-[2.2rem] justify-start"}>
                            {/* 只是PG游戏展示demo试玩按钮 */}
                            {/*{(item?.category_name === "Pragmaticplay" ||*/}
                            {/*    item?.category_name === "PP") && (*/}
                            {/*    <div*/}
                            {/*        onClick={() => demoPlayGameHandler({ ...item!, demo: 1 })}*/}
                            {/*        className={`flex h-[0.46rem] w-[1rem] items-center justify-center rounded-[.24rem] bg-[#11de68] text-[0.15rem] font-bold`}*/}
                            {/*    >*/}
                            {/*        {t("demo")}*/}
                            {/*    </div>*/}
                            {/*)}*/}
                            <div
                                onClick={() => playGameHandler(item!)}
                                // style={{
                                //     "--background-color": "#009d80",
                                //     "--border-color": "#009d80",
                                // }}
                                className={`flex h-[0.46rem] w-[1rem] items-center justify-center rounded-[.24rem] bg-[#11de68] text-[0.15rem] font-bold`}
                            >
                                {t("join")}
                            </div>
                        </div>
                    </div>
                </div>
            </Popup>

            <TipsModal title={"Tips"} ref={gameModelRef} getContainer={element.current}>
                <p className={"text-left text-[0.12rem] font-medium text-[#666]"}>
                    Há jogos inconclusos continuar o jogo
                </p>

                <div className={"mt-[0.0694rem] flex justify-center"}>
                    <Button
                        color={"primary"}
                        className={"mx-auto"}
                        style={{
                            "--background-color": "var(--primary-color)",
                            "--border-color": "var(--primary-color)",
                        }}
                        onClick={goGame}
                    >
                        para jogos
                    </Button>
                </div>
            </TipsModal>
        </>
    );
};

export default Card;
