import styles from './styles.module.scss';
import Spring from "@components/Spring";
import React, { useEffect, useState } from "react";
import new_icon from "@assets/promotion/new.png";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { getRedPackInfo } from "@features/redpackSlice";
import { formatTime } from "@utils/helpers";
import { reqGameActivity, reqRedpackCheck } from "@features/api";
import { getTurnplate } from "@features/turnplateSlice";
import { getActivityList, getActivityStatus } from "@features/activitySlice";
import LazyImgix from "@components/Imgix/LazyImgix";
import { getBonusList } from "@features/agentSlice";
import clock from "@assets/promotion/clock.json";
import Lottie from "lottie-react";
import { REQ_STATUS } from "@api/config";
import SmallLoading from "@components/SmallLoading";

import firstRecharge from "@assets/promotion2/firstRecharge.webp";
import holidaysGift from "@assets/promotion2/holidaysGift.png";
import holidaysAct from "@assets/promotion2/holidaysAct.png";

import { getFirstPayGift } from '@features/paySlice';
import usePaymentActions from '@hooks/usePaymentActions';
import { ROUTE_PATH } from '@constants/routes';
import boxHoliday from "@assets/bottomNav/boxHoliday.webp";
import iconHoliday from "@assets/bottomNav/iconHoliday.webp";
import { getHolidaysActInfo, getHolidaysGiftInfo } from '@features/mainSlice';

const WBonus = ({ close }) => {
    const navigate = useNavigate();
    const redpack = useSelector(getRedPackInfo);
    const turnplate = useSelector(getTurnplate);
    const agentBonus = useSelector(getBonusList);
    const dispatch = useDispatch();
    // const data=useSelector(getActivityList);
    const status = useSelector(getActivityStatus);
    const firstGiftInfo = useSelector(getFirstPayGift);
    const { getFirstPayGiftInfo } = usePaymentActions();


    // console.error("data:", data);


    useEffect(() => {
        if (data == null || data.length === 0) {
            dispatch(reqGameActivity());
        }
        //dispatch(reqRedpackCheck());
    }, []);
    const checkDot = (item) => {
        if (item.id === 1) {
            if (turnplate && turnplate.times > 0) {
                return true;
            }
        }
        else if (item.id === 2) {
            if (agentBonus && agentBonus.length > 0) {
                return true;
            }
        }
        else if (item.id === 3) {
            if (redpack && redpack.status === 1) {
                return true;
            }
        }
        return false;
    };
    // const checkRender
    const checkRenderLeft = (item) => {
        if (item.id === 3) { }
        return (
            <></>
        );
    };
    const checkRenderCD = (item) => {
        if (redpack == null) return (<></>);
        let status = redpack.status;
        if (status !== 0) return (<></>);
        let cdLeft = redpack.next_in_seconds;
        let cdLeftStr = formatTime(cdLeft);
        return (
            <div className={styles.item_right}>
                <div className={styles.clock_item}>
                    {cdLeftStr}
                    <Lottie animationData={clock} className={styles.clock_icon} />
                </div>
            </div>
        );
    };
    const checkRenderRight = (item) => {
        let isdot = checkDot(item);
        if (isdot) {
            return (
                <div className={styles.item_right}>
                    <img src={new_icon} className={`${styles.act_new} iconshake`} />
                </div>
            );
        }
        else {
            if (item.id === 3) {
                return checkRenderCD(item);
            }
        }
        return (
            <></>
        );
    };

    const renderTextWithLineBreaks = (text) => {
        return text.split(/(<br\s*\/?>)/gi).map((part, index) => {
            if (part.toLowerCase().startsWith('<br')) {
                return <br key={index} />;
            }
            return part;
        });
    };

    const Countdown = ({ targetDate }) => {
        const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(targetDate));

        function calculateTimeLeft(targetDate) {
            const difference = new Date(targetDate) - new Date();

            if (difference <= 0) {
                return { hours: '00', minutes: '00', seconds: '00' };
            }

            return {
                hours: String(Math.floor((difference / (1000 * 60 * 60)) % 24)).padStart(2, '0'),
                minutes: String(Math.floor((difference / (1000 * 60)) % 60)).padStart(2, '0'),
                seconds: String(Math.floor((difference / 1000) % 60)).padStart(2, '0')
            };
        }

        useEffect(() => {
            const timer = setInterval(() => {
                setTimeLeft(calculateTimeLeft(targetDate));
            }, 1000);

            return () => clearInterval(timer);
        }, [targetDate]);

        return (
            <div className={styles.countdown}>
                <div className={styles.item}>{timeLeft.hours}</div>
                <div className={styles.split}>:</div>
                <div className={styles.item}>{timeLeft.minutes}</div>
                <div className={styles.split}>:</div>
                <div className={styles.item}>{timeLeft.seconds}</div>
            </div>
        );
    };
    const renderItem = (item) => {
        return (
            <>
                {/* <LazyImgix src={item.img} alt={item.title} className={styles.banner} width={1350}></LazyImgix> */}
                <img src={item.img} alt="" className={styles.banner} />

                <div className={styles.title}>
                    {renderTextWithLineBreaks(item.title)}
                </div>
                <div className={styles.desc}>
                    {renderTextWithLineBreaks(item.content)}
                </div>

                {item.extra}

                <div className={styles.bottomTxt}>
                    <span>
                        {item.desc}
                    </span>

                    {item.button}
                </div>

                {item.redPoint}
            </>
        );
    };
    const handleClickItem = (link, target) => {
        if (link) {
            navigate(link);
        } else if (target) {
            global[target] && global[target]();
        }
    };

    let firstPayActive = true;
    let noFirstPay = !!firstGiftInfo?.has_purchased;
    let total_bonus = 53.97;
    if (!!firstGiftInfo && !!firstGiftInfo.gift_info) {
        total_bonus = firstGiftInfo.gift_info.total_bonus;
        if (firstGiftInfo.has_purchased && Date.now() / 1000 > firstGiftInfo.gift_info.expired) {
            firstPayActive = false;
        }
    }

    // first pay
    const { time_left, has_bonus } = getFirstPayGiftInfo();
    let leftTime = time_left ? time_left : 0;
    if (leftTime == 0) noFirstPay = true;

    // holidays gift
    const holidaysGiftInfo = useSelector(getHolidaysGiftInfo);
    let { user: holidaysGiftUser, status: holidaysGiftStatus } = holidaysGiftInfo;
    const [redPromotion, setRedPromotion] = useState(false);
    useEffect(() => {
        if (holidaysGiftUser?.left_times !== undefined) {
            setRedPromotion(holidaysGiftUser.left_times > 0);
        }
    }, [holidaysGiftUser]);

    // holidays activity
    const holidaysActInfo = useSelector(getHolidaysActInfo);
    let { user: holidaysActUser, status: holidaysActStatus } = holidaysActInfo;
    useEffect(() => {
        if (holidaysActUser?.left_times !== undefined) {
            setRedPromotion(holidaysActUser.left_times > 0);
        }
    }, [holidaysActUser]);

    let data = [
        {
            "id": 1,
            "order": 0,

            "link_game": 0,
            "link_module": "",
            "state": 127,
            img: firstRecharge,
            link: ROUTE_PATH.FIRSTDEPOSIT,
            target: "",
            status: firstPayActive,
            title: noFirstPay ? "You have obtained" : "LIMITED TIME<br>FIRST DEPOSIT",
            content: noFirstPay ? `$${total_bonus}` : "+270%",
            extra: (noFirstPay ? (
                <div className={styles.claimBtn}>CLAIM</div>
            ) : (<Countdown targetDate={Date.now() + leftTime * 1000} />)),
            desc: "LIMITED TIME FIRST DEPOSIT +270%",
            button: (
                <div className={styles.detail}>
                    <span>Detail</span>
                    {
                        has_bonus ? <div className={styles.redPoint}></div> : <></>
                    }

                </div>
            ),
            redPoint: <></>
        },
        {
            "id": 2,
            "order": 0,

            "link_game": 0,
            "link_module": "",
            "state": 127,
            img: holidaysGift,
            link: "",
            target: "showHolidaysGift",
            status: !!holidaysGiftStatus,
            title: "DEPOSIT TO GET",
            content: "115%<br>BONUS",
            extra: "",
            desc: "DEPOSIT TO GET 115% BONUS",
            button: (
                <div className={styles.detail}>
                    <span>Detail</span>
                    {
                        redPromotion ? <div className={styles.redPoint}></div> : <></>
                    }
                </div>
            ),
            redPoint: (
                redPromotion ?
                    <div className={styles.redTipHoliday}  >
                        <img src={boxHoliday} alt="" className={styles.boxHoliday} />
                        <div className={styles.tip}>
                            <img src={iconHoliday} alt="" className={styles.iconHoliday} />
                            <span>+{holidaysGiftUser?.left_times}</span>
                        </div>
                    </div>
                    :
                    <></>
            )
        },
        {
            "id": 3,
            "order": 0,
            "link_game": 0,
            "link_module": "",
            "state": 127,
            img: holidaysAct,
            link: "",
            target: "showHolidaysAct",
            status: !!holidaysActStatus,
            title: "DEPOSIT TO GET",
            content: "115%<br>BONUS",
            extra: "",
            desc: "DEPOSIT TO GET 115% BONUS",
            button: (
                <div className={styles.detail}>
                    <span>Detail</span>
                    {
                        redPromotion ? <div className={styles.redPoint}></div> : <></>
                    }
                </div>
            ),
            redPoint: <></>
        },
    ];
    const renderList = () => {
        return (
            <>
                {
                    data.map((item, index) => {
                        if (!item.status) return <></>;
                        return (
                            <button key={index} className={styles.act_item} onClick={() => handleClickItem(item.link, item.target)}>
                                {renderItem(item)}
                            </button>
                        );
                    })
                }
            </>
        );
    };
    return (
        <div className={styles.container}>
            <div className={styles.topArea}>
                {/* <p>100</p> */}
                <div className={styles.header}>
                    Promotion
                </div>
            </div>
            <div className={styles.centerArea}>
                {
                    status === REQ_STATUS.LOADING ? (<SmallLoading></SmallLoading>) : (
                        <Spring type="slideUp" className={styles.content}>
                            {renderList()}
                        </Spring>
                    )
                }
            </div>
        </div>
    );
};
export default WBonus;
