"use client";
import { GameListRep, searchGameListApi, SearchProps } from "@/api/home";
import Box from "@/components/Box";
import GroupCard from "@/components/Card/GroupCard";
import { useSearchStore } from "@/stores/useSearchStore";
import { Button, createErrorBlock, Mask, SearchBar } from "antd-mobile";
import { useTranslations } from "next-intl";
import { ChangeEvent, FC, MouseEvent, PropsWithChildren, useRef, useState } from "react";
interface Props {}
interface ContentProps {
    closeHandler: () => void;
}

const ErrorBlock = createErrorBlock({
    empty: <div className={"iconfont icon-meiyoushuju text-[0.5556rem] text-[#666]"}></div>,
    default: <div></div>,
});
const Content: FC<ContentProps> = (props) => {
    const t = useTranslations("HomePage");
    const { closeHandler } = props;
    const [games, setGames] = useState<GameListRep[]>([]);
    const searchBarRef = useRef(null);
    const [searchValue, setSearchValue] = useState("");

    const { history, setHistory, removeKey, removeAllKey } = useSearchStore();
    const [visible, setVisible] = useState(false);

    const params = useRef<SearchProps>({
        current_page: 1,
        page_size: 15,
        use_page: true,
        search_game_name: "",
    });

    const getGames = async (): Promise<GameListRep[] | undefined> => {
        return searchGameListApi(params.current).then((res) => {
            setVisible(!res.page.is_end);
            if (res.data) {
                return res.data;
            }
        });
    };
    const isPending = () =>
        games.length === 0 &&
        params.current.search_game_name === "" &&
        params.current.current_page === 1;
    const setSearchValueInit = (value: string, isPush = true) => {
        params.current.search_game_name = value;
        getGames().then((data) => {
            if (data && data.length > 0 && value.trim() !== "" && isPush) {
                setHistory(value);
            }
            data && setGames(data);
        });
    };

    // const func = debounce(setSearchValueInit, 500);
    // const changeHandler = (value: string) => {
    //     if (value) func(value);
    // };

    const blurHandler = (event: ChangeEvent<HTMLInputElement>) => {
        const value = event.target.value;
        if (value.trim() === "") return;
        setSearchValueInit(value);
    };
    const onCancel = () => {
        closeHandler();
        params.current.current_page = 1;
        params.current.search_game_name = "";
        setGames([]);
        setVisible(false);
    };

    // 历史记录单项点击事件
    const historyItemHandler = (key: string) => {
        if (key === params.current.search_game_name) return;
        setSearchValue(key);
        setSearchValueInit(key, false);
    };
    const removeHistoryItem = (event: MouseEvent<HTMLElement>, item: string) => {
        event.stopPropagation();
        removeKey(item);
    };
    const nextHandler = async () => {
        params.current.current_page++;
        return getGames().then((data) => data && setGames((games) => games.concat(data)));
    };

    return (
        <Box className={"flex h-[100dvh] flex-col"}>
            <div className={"home-search flex-shrink-0"}>
                <SearchBar
                    className={"rounded-[0.05rem] bg-[#191919]"}
                    style={{
                        "--background": "transparent",
                        "--height": "0.3rem",
                    }}
                    aria-hidden="true"
                    placeholder={t("search")}
                    showCancelButton={() => true}
                    ref={searchBarRef}
                    // onChange={changeHandler}
                    value={searchValue}
                    onChange={(val) => setSearchValue(val)}
                    onBlur={blurHandler}
                    onCancel={onCancel}
                />
                <div
                    className={
                        "h-[.5rem] text-center text-[0.12rem] text-[#6e6e6e]" + " leading-[.5rem]"
                    }
                >
                    {t("searchTips")}
                </div>

                {history.length ? (
                    <div className={"flex items-center justify-between"}>
                        <header> {t("searchHistory")} </header>
                        <i
                            className="iconfont icon-guanbi cursor-pointer text-[0.08rem]"
                            onClick={() => removeAllKey()}
                        ></i>
                    </div>
                ) : null}
                <div className={"mt-[0.05rem] flex flex-wrap"}>
                    {history.map((item, index) => {
                        return (
                            <div
                                className={
                                    "flex items-center bg-[#1a1a1a]" +
                                    " text-[#b3b3b3]" +
                                    " m-[0.05rem] rounded-[0.04rem] px-[0.07rem]" +
                                    " py-[0.03rem]"
                                }
                                onClick={() => historyItemHandler(item)}
                                key={index}
                            >
                                <span className={"mr-[0.2rem]"}>{item}</span>
                                <i
                                    className="iconfont icon-guanbi cursor-pointer text-[0.08rem]"
                                    onClick={(event) => removeHistoryItem(event, item)}
                                ></i>
                            </div>
                        );
                    })}
                </div>
            </div>
            <div className={"mt-[0.13rem] flex-1 overflow-y-scroll"}>
                {games.length ? (
                    <GroupCard data={games} row={1} />
                ) : (
                    <ErrorBlock
                        status={isPending() ? "default" : "empty"}
                        description={""}
                        title={isPending() ? "" : "no data"}
                    />
                )}
                <div className={"mt-[0.1rem]"}>
                    {visible && (
                        <Button
                            fill={"none"}
                            color={"default"}
                            loading="auto"
                            onClick={async () => {
                                await nextHandler();
                            }}
                            block={true}
                            style={{ "--background-color": "#1a1a1a", "--text-color": "#c4c4c4" }}
                        >
                            {t("searchButton")}
                        </Button>
                    )}
                </div>
            </div>
        </Box>
    );
};
const HomeSearch: FC<PropsWithChildren<Props>> = (props) => {
    const t = useTranslations("HomePage");
    const [visible, setVisible] = useState(false);
    const handler = () => {
        setVisible(true);
    };
    return (
        <>
            <div
                onClick={handler}
                className={
                    "flex items-center rounded-[0.03rem] bg-[#191919] py-[5px]" +
                    " px-[10px] text-[#6e6e6e]"
                }
            >
                <i className={"iconfont icon-sousuo1 mr-[0.0833rem] text-[0.16rem]"}></i>
                <span className={"text-[0.12rem]"}>{t("search")}</span>
            </div>
            <Mask visible={visible} opacity={0.9} getContainer={null}>
                <Content closeHandler={() => setVisible(false)} />
            </Mask>
        </>
    );
};

export default HomeSearch;
