"use client";
import { ContactType, getContactsApi, getSidebarActivitiesApi } from "@/api/config";
import { BannerRep, GroupType } from "@/api/home";
import Box from "@/components/Box";
import dialogManage from "@/dialog/manager";
import { Link, usePathname, useRouter } from "@/i18n/routing";
import { useProviderStore } from "@/stores/useProvider";
import { useSystemStore } from "@/stores/useSystemStore";
import { useWalletStore } from "@/stores/useWalletStore";
import { server } from "@/utils/client";
import clsx from "clsx";
import { useLocale } from "next-intl";
import Image from "next/image";
import React, { FC, PropsWithChildren, useEffect, useMemo, useRef, useState } from "react";
import styles from "./style.module.scss";

const getGames = async () => {
    return server
        .request<GroupType[]>({
            url: "/v1/api/front/game_list",
            method: "POST",
        })
        .then((res) => {
            if (res.code === 200) return res.data;
            return [];
        });
};

const registePromoClick = (activity_id: number) => {
    return server
        .request({
            url: "/v1/api/front/activity_promotion_click",
            method: "post",
            data: { activity_id },
        })
        .then((res) => {
            if (res.code === 200) return res.data;
            return [];
        });
};

interface Props {}

const tabs = [
    { name: "casino", id: 1, icon: "pro-niuyouguo" },
    { name: "promocoes", id: 2, icon: "pro-shengriliwu" },
];

enum PageEnum {
    "home",
    "sports",
    "help",
    "promo",
    "deposit",
    "download",
    "none",
    "profile",
    "gameList2",
    "withdraw",
    "Vip",
}

const PageEnumMap = new Map<PageEnum, { url: string }>([
    [PageEnum.home, { url: "/" }],
    [PageEnum.sports, { url: "/promo" }],
    [PageEnum.help, { url: "/help" }],
    [PageEnum.Vip, { url: "/vip" }],
    [PageEnum.promo, { url: "/promo" }],
    [PageEnum.deposit, { url: "/deposit" }],
    [PageEnum.withdraw, { url: "/deposit?target=2" }],
    [PageEnum.download, { url: "/download" }],
    [PageEnum.profile, { url: "/profile" }],
]);

const Sidebar: FC<PropsWithChildren<Props>> = (props) => {
    // const t = useTranslations("Sidebar");
    const { providers, setProviders } = useProviderStore();
    // todo Wallet
    const { wallet } = useWalletStore();

    const locale = useLocale();
    // const swiper = useSwiper();
    const router = useRouter();
    const tab = useRef<HTMLDivElement>(null);
    const bgRef = useRef<HTMLDivElement>(null);
    const [isShowAll, setIsShowAll] = useState(false);

    const pathname = usePathname();
    const { isCollapse, setCollapse, service, show_free_game, show_again_game } = useSystemStore(
        (state) => ({
            isCollapse: state.isCollapse,
            setCollapse: state.setCollapse,
            service: state.service,
            show_free_game: state.show_free_game,
            show_again_game: state.show_again_game,
        })
    );

    React.useEffect(() => {
        console.log(pathname);
        setTimeout(() => {
            const dom: any = document.querySelector("#globalMask");
            if (dom) dom.style.display = "none";
        }, 500);
        // Router.events.on("routeChangeComplete", () => {
        //     console.log(99990);
        // });
        // setTimeout(() => {
        //     Router.events.emit("routeChangeComplete");
        // }, 10000);
    }, [pathname]);

    React.useEffect(() => {
        if (!providers || providers.length === 0) {
            getGames().then((res) => {
                const providersData = res[0].category.filter((item) => item.type === 2);
                if (providersData.length === 0) return [] as any;
                setProviders(providersData[0].game_list);
            });
        }
    }, [providers, setProviders]);

    const tabHandler = (index: PageEnum, isAction = true) => {
        bgRef.current?.setAttribute(
            "style",
            `transform: translateX(${tab.current?.clientWidth! * index}px)`
        );
        if (isAction) {
            const curToPage = PageEnumMap.get(index);
            if (curToPage) {
                router.push(curToPage.url);
                setCollapse(false);
            }
        }

        return index;
    };
    const registePromo = (id?: number) => {
        if (!id) return;
        registePromoClick(id);
    };
    useEffect(() => {
        if (pathname === "/") {
            tabHandler(PageEnum.home, false);
        } else {
            tabHandler(PageEnum.sports, false);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isCollapse]);

    const [contacts, setContacts] = useState<ContactType[]>();

    const [cardData, setCardData] = useState<BannerRep[]>([]);

    useEffect(() => {
        getContactsApi().then((res) => {
            setContacts(res.data.filter((item) => item.show_bar === 1));
        });

        getSidebarActivitiesApi().then((res) => {
            console.log(33, res.data);
            setCardData(res.data);
        });
    }, []);

    const serviceUrl: string = useMemo(() => {
        if (!service) return "";
        const result = service.filter((item) => item.status === 1);
        return result[0]?.url || "";
    }, [service]);

    const listCfg = useMemo(() => {
        return [
            {
                text: "Seleção de idioma",
                icon: `/sidebar/${locale}.webp`,
                handle: () => {
                    setCollapse(false);
                    dialogManage.showDialog("LanguageSelect");
                },
            },
            {
                text: "Baixar APP",
                icon: "/sidebar/app.webp",
                handle: () => {
                    setCollapse(false);
                    router.push("/download");
                },
            },
            {
                text: "atendimento ao Cliente",
                icon: "/sidebar/service.webp",
                renderWrap: (children: any) =>
                    serviceUrl ? <Link href={serviceUrl}>{children}</Link> : "",
            },
            {
                text: "VIP",
                icon: "/sidebar/vip.webp",
                handle: () => {
                    setCollapse(false);
                    tabHandler(PageEnum.Vip);
                },
            },
            {
                text: "FAQ",
                icon: "/sidebar/faq.webp",
                handle: () => {
                    setCollapse(false);
                    tabHandler(PageEnum.help);
                },
            },
            {
                text: "Envie-nos um e-mail",
                icon: "/sidebar/email.webp",
                noRender: !(contacts && contacts?.length > 0),
                handle: () => {
                    if (contacts) {
                        const a = document.createElement("a");
                        a.href = `mailto:${contacts[0].email}`;
                        a.target = "email";
                        a.click();
                    }
                },
            },
        ];
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [serviceUrl, locale]);

    const walletCfg = useMemo(() => {
        const result: any = [
            // {
            //     text: "Saldo",
            //     icon: "/sidebar/saldo.webp",
            //     textStyle: { fontSize: ".12rem" },
            //     value: wallet.score || 0,
            // },
            // {
            //     text: "Bônus",
            //     icon: "/sidebar/bonus.webp",
            //     textStyle: { fontSize: ".12rem" },
            //     value: wallet.point || 0,
            // },
        ];
        if (show_free_game === 1) {
            result.push({
                text: "Carteira grátis",
                icon: "/sidebar/free.webp",
                value: wallet.free_score || 0,
                url: "/freeGames",
            });
        }
        if (show_again_game === 1) {
            result.push({
                text: "Carteira duplicada",
                icon: "/sidebar/money.webp",
                textStyle: { fontSize: ".09rem" },
                value: wallet.lose_score || 0,
                url: "/replayGames",
            });
        }
        return result;
    }, [wallet, show_free_game, show_again_game]);

    const todoHandler = (item: any) => {
        setCollapse(false);
        router.push({
            pathname: `/gameList2?provider_id=${item.id}`,
        });
    };
    const promotionHandle = (item: any) => {
        setCollapse(false);
        // router.push({
        //     pathname: `/gameList2?provider_id=${item.id}`,
        // });
    };
    return (
        <Box pt={false} className={"h-[100%] bg-[#1e252b] px-[0px]"}>
            <div className={"relative flex h-[100%] flex-col"}>
                <div className={"sticky top-[0] px-[.12rem]"}>
                    <div className={"mb-[.1rem] flex items-center pt-[10px]"}>
                        <div
                            onClick={() => {
                                setCollapse(false);
                            }}
                            className="mr-[.06rem] rounded-[.06rem] bg-[#121617] px-[.08rem] py-[.06rem]"
                            style={{ transform: isCollapse ? "rotate(180deg)" : "rotate(0deg)" }}
                        >
                            <i className="iconfont icon-zhankai1 text-[.16rem] text-[#fff]"></i>
                        </div>
                        <div className={"flex-1"}>
                            <Image src={"/logo2.webp"} alt={"logo"} width={130} height={110} />
                        </div>
                    </div>
                </div>
                <div className="flex-1 overflow-scroll px-[.12rem]">
                    <div className={styles.providerBox}>
                        {providers?.map((item, idx) => {
                            if (!isShowAll && idx > 6) return null;
                            return (
                                <div
                                    className={styles.providerItem}
                                    onClick={() => todoHandler(item)}
                                    key={item.id}
                                >
                                    <img src={item.game_icon} alt="" />
                                </div>
                            );
                        })}
                        <div
                            className={styles.providerItem}
                            onClick={() => {
                                setCollapse(false);
                                router.push("/gameList?pageType=1&name=History");
                            }}
                        >
                            <img src={"/home/history.webp"} alt="" />
                        </div>
                        <div
                            className={styles.providerItem}
                            onClick={() => {
                                setCollapse(false);
                                router.push("/gameList?pageType=2&name=Favorite");
                            }}
                        >
                            <img src={"/home/favorite.webp"} alt="" />
                        </div>
                        {!isShowAll && providers.length > 6 && (
                            <div
                                className={styles.providerItem}
                                onClick={() => {
                                    setIsShowAll(true);
                                }}
                                style={{
                                    background: "url('/home/placehold.webp')",
                                    backgroundSize: "100%",
                                }}
                            ></div>
                        )}
                    </div>
                    {walletCfg?.length && (
                        <>
                            <div className={clsx(styles.sideTitle, "mt-[.06rem]")}>
                                <i
                                    className={clsx(
                                        "iconfont icon-qianbao11 text-[.26rem]",
                                        styles.icon
                                    )}
                                ></i>
                                <span>Carteira</span>
                            </div>
                            <div className={styles.qianbao}>
                                {walletCfg.map((item: any) => {
                                    return (
                                        <Link
                                            href={item.url}
                                            key={item.text}
                                            prefetch
                                            onClick={() => setCollapse(false)}
                                            className={styles.qianbaoItem}
                                        >
                                            <img
                                                className="mr-[.06rem] w-[.3rem]"
                                                src={item.icon}
                                                alt=""
                                            />
                                            <div>
                                                <div className="text-[.16rem] leading-[1.2]">
                                                    {item.value}R
                                                </div>
                                                <div
                                                    className="text-[.1rem] leading-[1]"
                                                    style={{ ...(item.textStyle || {}) }}
                                                >
                                                    {item.text}
                                                </div>
                                            </div>
                                        </Link>
                                    );
                                })}
                            </div>
                        </>
                    )}

                    {cardData.length > 0 && (
                        <div className={clsx(styles.sideTitle, "my-[.06rem]")}>
                            <i
                                className={clsx("iconfont icon-liwu text-[.24rem]", styles.icon)}
                            ></i>
                            <span>Promoções</span>
                        </div>
                    )}

                    <div className={styles.promotionBox}>
                        {cardData.map((item) => {
                            return (
                                <Box
                                    key={item.id}
                                    action={item.action_type}
                                    actionData={item.action_params}
                                    className={styles.promoItem}
                                    onBeforeHandler={() => registePromo(item.id)}
                                    pb={false}
                                    pt={false}
                                    pl={false}
                                    pr={false}
                                >
                                    <div
                                        key={item.id}
                                        className={styles.promotionItem}
                                        onClick={() => promotionHandle(item)}
                                    >
                                        <img src={item.content} alt="" />
                                    </div>
                                </Box>
                            );
                        })}
                        {/* <div className={styles.promotionItem}>
                            <img src="/sidebar/promotion.webp" alt="" />
                        </div>
                        <div className={styles.promotionItem}>
                            <img src="/sidebar/promotion.webp" alt="" />
                        </div>
                        <div className={styles.promotionItem}>
                            <img src="/sidebar/promotion.webp" alt="" />
                        </div>
                        <div className={styles.promotionItem}>
                            <img src="/sidebar/promotion.webp" alt="" />
                        </div> */}
                    </div>

                    {listCfg.map((item) => {
                        if (item.noRender) return null;
                        if (item.renderWrap) {
                            const Wrapper = item.renderWrap;
                            if (React.isValidElement(Wrapper)) {
                                return (
                                    <Wrapper key={item.text}>
                                        <div className={styles.signalItem}>
                                            <img src={item.icon} alt="" />
                                            <div>{item.text}</div>
                                        </div>
                                    </Wrapper>
                                );
                            }
                            return null;
                        }
                        return (
                            <div
                                className={styles.signalItem}
                                key={item.text}
                                onClick={item.handle}
                            >
                                <img src={item.icon} alt="" />
                                <div>{item.text}</div>
                            </div>
                        );
                    })}
                </div>
                <div
                    className={clsx(
                        "flex items-center justify-between bg-[#2b363f] p-[.1rem] font-bold text-[#000]",
                        styles.footer
                    )}
                >
                    <button onClick={() => tabHandler(PageEnum.deposit)}>Depósito</button>
                    <button onClick={() => tabHandler(PageEnum.withdraw)}>Sacar</button>
                </div>

                {/*  card*/}
                {/* <div className={"mt-[0.2rem] grid grid-cols-1 gap-[0.0833rem]"}>
                    {cardData.map((item, index) => {
                        return (
                            <Box
                                className={"shadow-md"}
                                none={true}
                                key={index}
                                onBeforeHandler={() => {
                                    // 关闭侧边栏按钮
                                    setCollapse(false);
                                    // 关闭swiper
                                    // swiper.slideNext();
                                }}
                                action={item.action_type}
                                actionData={item.action_params}
                            >
                                <div className="mb-[.1rem] flex h-[0.5556rem] justify-center overflow-hidden rounded-[0.1rem] border-[1px] border-[#eba9ff]">
                                    <img
                                        src={item.content}
                                        alt=""
                                        className={"h-[100%] w-[100%]"}
                                    />
                                </div>
                            </Box>
                        );
                    })}
                </div> */}

                {/*  gift */}
                {/*<section*/}
                {/*    onClick={() => tabHandler(PageEnum.promo)}*/}
                {/*    className={"my-[0.11rem] flex items-center text-[0.15rem]" + " text-[#fff]"}*/}
                {/*>*/}
                {/*    <div className={"flex-1"}>*/}
                {/*        <span*/}
                {/*            className={*/}
                {/*                "iconfont icon-liwulipinjiangpin mr-[0.0694rem]" +*/}
                {/*                " text-[0.16rem] text-[#999]"*/}
                {/*            }*/}
                {/*        ></span>*/}
                {/*        <span> {t("promocoes")} </span>*/}
                {/*    </div>*/}
                {/*    /!*<span className={"iconfont icon-xiangyou1"}></span>*!/*/}
                {/*</section>*/}

                {/* <section
                    onClick={() => tabHandler(PageEnum.deposit)}
                    className={"my-[0.16rem] flex items-center text-[0.15rem]" + " text-[#fff]"}
                >
                    <div className={"flex-1"}>
                        <span
                            className={
                                "iconfont icon-qianbao3 mr-[0.0694rem] text-[0.16rem] text-[#fff]"
                            }
                        ></span>
                        <span> {t("deposit")} </span>
                    </div>
                </section>

                <section
                    onClick={() => tabHandler(PageEnum.help)}
                    className={"my-[0.16rem] flex items-center text-[0.15rem]" + " text-[#fff]"}
                >
                    <div className={"flex-1"}>
                        <span
                            className={
                                "iconfont icon-bangzhu mr-[0.0694rem] text-[0.16rem] text-[#fff]"
                            }
                        ></span>
                        <span> {t("ajude")} </span>
                    </div>
                </section>
                <section
                    onClick={() => tabHandler(PageEnum.download)}
                    className={"my-[0.16rem] flex items-center text-[0.15rem]" + " text-[#fff]"}
                >
                    <div className={"flex-1"}>
                        <span
                            className={
                                "iconfont icon-header-18 mr-[0.0694rem] text-[0.16rem] text-[#fff]"
                            }
                        ></span>
                        <span> {t("download")} </span>
                    </div>
                </section>

                <section className={"text-[0.15rem]" + " text-[#fff]"}>
                    {contacts?.map((item, index) => (
                        <a
                            key={index}
                            href={`mailto:${item.email}`}
                            className={"my-[0.16rem] flex items-center text-[#fff]"}
                        >
                            <span
                                className={
                                    "iconfont icon-duanxinguanli mr-[0.09rem] text-[0.16rem] text-[#fff]"
                                }
                            ></span>
                            <span> {t("email")} </span>
                        </a>
                    ))}
                </section>

                <section className={"mt-[0.11rem] text-[#fff]"}>{t("coumnidade")}</section> */}
            </div>
        </Box>
    );
};
export default Sidebar;
