import Modal from "@mui/material/Modal";
import Fade from "@mui/material/Fade";
import styles from "./styles.module.scss";
import { useEffect, useState } from "react";
import Grow from "@mui/material/Grow";
import closeImg from '@assets/checkIn/com_tanc_X.png';
import { useDispatch, useSelector } from "react-redux";
import { getCheckInData, getCheckInStatus, getNextGetTime } from "@features/checkInSlice";
import { useNavigate } from "react-router-dom";
import { ROUTE_PATH } from "@constants/routes";
import { reqCheckinCheck, reqCheckinGet, reqRedpackCheck } from "@features/api";
import { REQ_STATUS } from "@api/config";
import SmallLoading from "@components/SmallLoading";
import { formatTime, localStorageGet, localStorageSet } from "@utils/helpers";
import { getPopFirst } from "@features/mainSlice";
import { getFirstPayMulti } from "@features/paySlice";
const i18n = global.i18n;
const imgList = {
    1: {
        src: require("@assets/checkIn/1.png"),
        height: "3.2rem"
    },
    2: {
        src: require("@assets/checkIn/1.png"),
        height: "3.2rem"
    },
    3: {
        src: require("@assets/checkIn/2.png"),
        height: "3.6rem"
    },
    4: {
        src: require("@assets/checkIn/3.png"),
        height: "3.9rem"
    },
    5: {
        src: require("@assets/checkIn/3.png"),
        height: "3.9rem"
    },
    6: {
        src: require("@assets/checkIn/4.png"),
        height: "4.3rem"
    },
    7: {
        src: require("@assets/checkIn/5.png"),
        height: "3.7rem"
    }
};
const objInfo = {
    timer: null
};
const WCheckIn = ({ close }) => {
    const [open, setOpen] = useState(false);
    const checkInData = useSelector(getCheckInData);
    const status = useSelector(getCheckInStatus);
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const NextGetTime = useSelector(getNextGetTime);
    const [leftTime, setLeftTime] = useState(0);
    const popFirst = useSelector(getPopFirst);
    const firstPayMulti = useSelector(getFirstPayMulti);

    const show = (type) => {
        setOpen(true);
    };
    const hide = () => {
        setOpen(false);
    };
    const onClose = () => {
        hide();
        global.openNextPopup();
    };
    useEffect(() => {
        const checkIn = {
            show,
            hide
        };
        global.checkIn = checkIn;
    }, []);

    const resetTimer = () => {
        if (objInfo.timer != null) {
            clearInterval(objInfo.timer);
            objInfo.timer = null;
        }
    };
    useEffect(() => {
        // dispatch(reqCheckinCheck());
        if (checkInData.RewardDay == null || checkInData.RewardDay.length === 0) {
            dispatch(reqCheckinCheck());
        }
        return () => {
            resetTimer();
        };
    }, []);
    useEffect(() => {
        resetTimer();
        let now = Date.now();
        let left = NextGetTime - now;
        if (left > 0) {
            setLeftTime(left);
            objInfo.timer = setInterval(() => {
                now = Date.now();
                left = NextGetTime - now;
                if (left <= 0) {
                    left = 0;
                    dispatch(reqCheckinCheck());
                    resetTimer();
                }
                setLeftTime(left);
            }, 1000);
        }
    }, [NextGetTime]);
    const checkFirstPay = () => {
        if (!popFirst) return;
        if (firstPayMulti == null) return;
        let key = "first_open_time";
        let now = Date.now();
        let lst = Number(localStorageGet(key, 0));
        let delta = now - lst;
        // if (delta<86400000){
        //     return false;
        // }
        global.showFirstPay();
        localStorageSet(key, Date.now());
    };
    const onOpenPay = () => {
        hide();
        navigate("/" + ROUTE_PATH.PAY, { replace: true });
    };
    const onCheckInCB = (payload) => {
        if (payload && payload.code === 200) {
            global.showDropCoins();
            onClose();
        }
        // else if (payload&&payload.code===301)
        // {
        //     let data={
        //         content:i18n.t("CheckIn.must_recharge"),
        //         sureLabel:i18n.t("CheckIn.btn_to_recharge"),
        //         sureCB:onOpenPay,
        //     }
        //     global.msgBoxShow(data)
        // }
    };
    const onCheckIn = (cashNum) => {
        if (status.CheckInGet === REQ_STATUS.LOADING) return;
        if (leftTime > 0) return;
        dispatch(reqCheckinGet({
            cashNum: cashNum,
            callback: onCheckInCB
        }));
    };
    const renderBonusList = () => {
        let RewardDay = checkInData.RewardDay;
        if (RewardDay == null) RewardDay = [];
        let rowData = [
            RewardDay.slice(0, 4),
            RewardDay.slice(4, 7),
        ];
        let nDayNumber = checkInData.NextDayNumber;
        if (nDayNumber > 7) nDayNumber = 7;
        let cbRecord = checkInData.cbRecord;
        let itemIndex = 0;
        return (
            <div className={styles.list_con}>
                {
                    rowData.map((rowList, rindex) => {
                        return (
                            <div key={rindex} className={styles.item_con}>
                                {
                                    rowList.map((item, index) => {
                                        let isDone = cbRecord[itemIndex];
                                        itemIndex++;
                                        return (
                                            <div key={index} className={`${styles.item} ${styles['item_' + item]}`}>
                                                <button className={`${styles.item_bg} ${nDayNumber === item ? styles.item_bg_today : ''} ${isDone === 1 ? styles.item_bg_recived : ''}`}>
                                                    <span className={styles.title}>{i18n.t("CheckIn.day" + item)}</span>
                                                    <div className={styles.img_con}>
                                                        <img src={imgList[item].src} style={{ height: imgList[item].height, width: "auto" }} />
                                                    </div>
                                                </button>
                                                {
                                                    isDone === 1 ? (
                                                        <div className={styles.item_checked}>
                                                            <img src={require("@assets/checkIn/img_sure.png")} />
                                                        </div>
                                                    ) : (<></>)
                                                }
                                            </div>
                                        );
                                    })
                                }
                            </div>
                        );
                    })
                }
            </div>
        );
    };
    const renderButtons = () => {
        let nDayNumber = checkInData.NextDayNumber;
        if (nDayNumber > 7) nDayNumber = 7;
        let RewardScore = checkInData.RewardScore;
        let cashNum = RewardScore[nDayNumber - 1];
        return (
            <div className={styles.buttons_con}>
                <button className={`${styles.btn_base} ${styles.btn_blue}`} onClick={onOpenPay}>
                    <span className={styles.text_con}>
                        {i18n.t("CheckIn.getMore")}
                    </span>
                </button>
                <button className={`${styles.btn_base} ${styles.btn_yellow}`} onClick={() => {
                    onCheckIn(cashNum);
                }}>
                    <img src={require("@assets/checkIn/img_jinbi.png")} className={styles.img_coin} />
                    {
                        status.CheckInGet === REQ_STATUS.LOADING ? (<SmallLoading fill={"#FFF"}></SmallLoading>) : (
                            <>
                                {
                                    leftTime <= 0 ? (
                                        <div className={styles.text_take}>
                                            {i18n.t("CheckIn.take")}
                                            <span>{global.DOLLAR + cashNum}</span>
                                        </div>
                                    ) : (
                                        <div className={styles.text_left}>
                                            <span className={styles.left_title}>{i18n.t("CheckIn.last_get")}</span>
                                            <span className={styles.left_timer}>{formatTime(leftTime, true)}</span>
                                        </div>
                                    )
                                }
                            </>
                        )
                    }
                </button>
            </div>
        );
    };
    const renderMain = () => {
        let RewardDay = checkInData.RewardDay;
        let isLoading = !(RewardDay != null && RewardDay.length > 0);
        return (
            <Grow in={open} timeout={500}>
                <div className={styles.check_con}>
                    <div className={styles.title_con}>
                        {i18n.t("CheckIn.title")}
                        <button className={styles.close} onClick={onClose}>
                            <img src={closeImg} alt="close" />
                        </button>
                    </div>
                    <div className={styles.content_con}>
                        {
                            isLoading ? (<SmallLoading fill={"#fff"}></SmallLoading>) : (
                                <>
                                    {renderBonusList()}
                                    {renderButtons()}
                                </>
                            )
                        }

                    </div>
                </div>
            </Grow>
        );
    };
    return (
        <>
            <Modal open={open} onClose={onClose} closeAfterTransition>
                <Fade in={open} timeout={500}>
                    <div className={styles.container}>
                        <div className={styles.content}>
                            {renderMain()}
                        </div>
                    </div>
                </Fade>
            </Modal>
        </>
    );
};
export default WCheckIn;