import LazyImage from '@components/LazyImage';
import styles from './styles.module.scss';
import topImg from '@assets/firstPay/top_bg.webp'
import coinImg from "@assets/firstPay/coin.webp"
import finishImg from "@assets/firstPay/icon_finish.webp";
import CountDown from '@components/CountDown/CountDown';
import WRecharge from '@widgets/WRecharge';
import { useDispatch, useSelector } from 'react-redux';
import { getFirstPayGift, getFirstPayGiftClaimStatus } from '@features/paySlice';
import { useEffect, useRef, useState } from 'react';
import { getCountDown, isFrequentTap } from '@utils/helpers';
import usePaymentActions from '@hooks/usePaymentActions';

import step1Img from "@assets/firstPay/step_1.webp";
import step1Img1 from "@assets/firstPay/step_1_1.webp";
import setp2Img from "@assets/firstPay/step_2.webp";
import setp3Img from "@assets/firstPay/step_3.webp";
import checkInImg from "@assets/firstPay/check_in.webp";
import borderImg from "@assets/firstPay/board_bg.webp";
import SvgIcon from '@components/SvgIcon';
import { reqFirstPayGiftClaim } from '@features/api';
import { REQ_STATUS } from '@api/config';

const i18n = global.i18n;

const RewardType = {
    Day: "day_reward",
    Bonus: "betting_bonus",
    Task: "betting_task",
}

const RewardStatus = {
    //不可领
    None: 0,
    //可以领
    Active: 1,
    //已领取
    Collected: 2,
    //已过期
    Expired: 3,
}

const RewardBox = ({ children, title, type, state = -1, onClick = null }) => {
    var disable = true;
    var completed = true;
    switch (state) {
        case RewardStatus.None:
            disable = true;
            completed = false;
            break;

        case RewardStatus.Active:
            disable = false;
            completed = false;
            break;

        case RewardStatus.Collected:
            disable = true;
            completed = true;
            break;

        case RewardStatus.Expired:
            disable = true;
            completed = false;
            break;
    }

    const handleClick = () => {
        if (isFrequentTap(`first_deposit_reward_${type}`)) return;
        onClick && onClick(type)
    }

    return (
        <div className={`${styles.reward_box} ${completed ? styles.reward_done : ""}`}>
            <div className={styles.title}>
                <span>{title}</span>
                <button
                    disabled={disable}
                    onClick={handleClick}
                >
                    Receive
                </button>
            </div>

            {children}

            {
                completed && <div className={styles.done_flag}>
                    <img src={finishImg} />
                </div>
            }
        </div >
    )
}

const WFirstDeposit = () => {
    // const firstPayGift = useSelector(getFirstPayGift);
    // const leftTimes = firstPayGift.time_left;
    // const total_bonus = firstPayGift.gift_info.total_bonus;
    // const gift_id = firstPayGift.gift_info?.gift_id;
    // const gift_name = firstPayGift.gift_info?.gift_name;
    // const list = firstPayGift.list;

    const { getFirstPayGiftInfo } = usePaymentActions();
    var giftInfo = getFirstPayGiftInfo();
    const total_bonus = giftInfo.total_bonus;
    const gift_id = giftInfo.gift_id;
    const gift_name = giftInfo.gift_name;
    const has_purchased = giftInfo.has_purchased;
    const expired_times = getCountDown(giftInfo.expired);
    const claimStatus = useSelector(getFirstPayGiftClaimStatus);

    const [deposit, setDeposit] = useState(0);
    const [bonus, setBonus] = useState(0);
    const [total, setTotal] = useState(0);
    const dispatch = useDispatch();

    useEffect(()=>{
        // adjust 曝光充值页面
        if (global.enterRechargeType == 1) {
            global.tracker.trackEvent("enter_recharge_page_first_pay");
            global.tracker.trackEvent("enter_recharge_page_first_pay_count");
        } else if (global.enterRechargeType == 2) {
            global.tracker.trackEvent("enter_recharge_page_vip_hint");
            global.tracker.trackEvent("enter_recharge_page_vip_hint_count");
        }
    }, [])

    const onGoodsSelect = (idx) => {
        let item = giftInfo.list[idx];
        let mul = total_bonus / 100;
        let money = item.favorable_price
        setDeposit(money);
        setBonus(((mul - 1) * money).toFixed(2));
        setTotal(((mul) * money).toFixed(2));
    }

    const renderPsBox = () => {
        return (
            <div className={styles.ps_box}>
                <div>
                    <span>New Players Only: First Deposit Offer! Deposit now and get 100% deposit amount + 170% deposit bonus.</span>
                    <p>
                        <span>Benefit One:</span><br />
                        1. On the day of the deposit, 120% of the deposit amount will be automatically credited to your game balance immediately.
                    </p>

                    <p>
                        <span>Benefit Two:</span><br />
                        1. Within seven days of the deposit, you can claim a reward each day, valid for that day only.<br />
                        2. You can claim up to 20% of the deposit amount in total.<br />
                        3. Detailed rules: On the second day after the deposit, you can claim a bonus of 2.5% of the deposit amount; on the third day, you can claim 2.5% of the deposit amount; on the fourth day, you can claim 3% of the deposit amount; on the fifth day, you can claim 3% of the deposit amount; on the sixth day, you can claim 4% of the deposit amount; on the seventh day, you can claim 5% of the deposit amount.
                    </p>

                    <p>
                        <span>Benefit Three:</span><br />
                        1. Activate Betting Task One: After depositing, 50% of the deposit amount will go into the prize pool, and you can earn $2 each time your bet reaches 100.<br />
                        2. Activate Betting Task Two: After depositing, when your bet amount reaches 60 times the deposit amount, you can receive a one-time reward of 80% of the deposit amount.
                    </p>

                    <p>
                        <span>Special Notes:</span><br />
                        1. All benefits from the deposit can only be enjoyed within seven days; expired benefits will be voided.<br />
                        2. The maximum deposit limit for participation in the promotion is $1000, and any amount over $1000 will not be included in the promotion.<br />
                        3. All bonuses will be allocated to the game balance.<br />
                        4. The final interpretation of this promotion belongs to "USSlot777"
                    </p>
                </div>
            </div>
        )
    }

    const renderNotpurchase = () => {
        return (
            <div className={styles.container}>
                <div className={styles.top_box}>
                    <div className={styles.title_lbl}>
                        {i18n.t("links.route_title.first_deposit")}
                    </div>
                    <div className={`${styles.lbl_bonus} amount-yellow`}>Bonus +{total_bonus}%</div>
                    <CountDown times={giftInfo.time_left} />
                    <div className={styles.des_box}>
                        <div className={styles.des_item}>
                            <LazyImage className={styles.icon} src={coinImg} alt={i18n.t("firstDeposit.tis_1")} />
                            <p>{i18n.t("firstDeposit.tis_1")}</p>
                        </div>

                        <div className={styles.des_item}>
                            <LazyImage className={styles.icon} src={coinImg} alt={i18n.t("firstDeposit.tis_2")} />
                            <p>{i18n.t("firstDeposit.tis_2")}</p>
                        </div>

                        <div className={styles.des_item}>
                            <LazyImage className={styles.icon} src={coinImg} alt={i18n.t("firstDeposit.tis_3")} />
                            <p>{i18n.t("firstDeposit.tis_3")}</p>
                        </div>
                    </div>
                </div>

                <div className={styles.scroll_box}>
                    <div className={styles.content}>
                        <div className={styles.tips_box}>
                            Deposit
                            <span>&nbsp;${deposit}&nbsp;</span>
                            + Bonus
                            <span>&nbsp;{bonus}&nbsp;</span>
                            = Total
                            <span>&nbsp;{total}&nbsp;</span>
                        </div>
                        <WRecharge goods={giftInfo.list} onSelect={onGoodsSelect} goodsName={gift_name} giftId={gift_id} />
                    </div>

                    <div className={styles.desc_box}>
                        <span>Deposit any amount <br /> ENJOY 3 BENEFITS INSTANTLY!</span>
                        <div className={styles.step_1}>
                            <img src={step1Img} className={styles.child} />
                            <button className={styles.child} >Deposit</button>
                            <img src={step1Img1} className={styles.child} />
                        </div>

                        <span className={styles.lbl_step}>Benefit One</span>
                        <span>Instantly receive 100% of the deposit amount + 20%<br /> deposit bonus</span>
                        <SvgIcon className={styles.svg} herf={"icon_Arrow_down"} />

                        <img src={setp2Img} className={styles.step_img} />
                        <span className={styles.lbl_step}>Benefit Two</span>
                        <span>Log in for seven consecutive days to receive daily<br />rewards</span>
                        <SvgIcon className={styles.svg} herf={"icon_Arrow_down"} />

                        <img src={setp3Img} className={styles.step_img} />
                        <span className={styles.lbl_step}>Benefit Three</span>
                        <span>Activate betting tasks and win a 130% deposit bonus</span>

                        <span className={styles.step_space}></span>
                        <span className={styles.lbl_step}>Login for 7 consecutive days</span>
                        <div className={styles.checkin_box}>
                            <img src={checkInImg} />
                            <div className={styles.days}>
                                <div className={styles.item}>
                                    <span>DAY2</span>
                                    <span>2.5%</span>
                                </div>

                                <div className={styles.item}>
                                    <span>DAY3</span>
                                    <span>2.5%</span>
                                </div >

                                <div className={styles.item}>
                                    <span>DAY4</span>
                                    <span>3%</span>
                                </div>

                                <div className={styles.item}>
                                    <span>DAY5</span>
                                    <span>3%</span>
                                </div>

                                <div className={styles.item}>
                                    <span>DAY6</span>
                                    <span>4%</span>
                                </div>

                                <div className={styles.item}>
                                    <span>DAY7</span>
                                    <span>5%</span>
                                </div>
                            </div>
                        </div>

                        <span className={styles.lbl_step}>Betting Missions</span>
                        <div className={styles.bet_box}>
                            <img src={borderImg} />
                            <span>Mission 1 <br /> Earn a $2 bonus for every 100 bets placed.</span>
                            <span>Mission 2 <br /> Complete wagering 60 times your deposit amount to claim a one-time 80% bonus (based on your deposit).</span>
                            <span></span>
                        </div>



                    </div>

                    {
                        renderPsBox()
                    }
                </div>
            </div>
        )
    }

    const renderMoney = (money) => {
        return (
            <span className={styles.money}>${money}</span>
        )
    }

    const onClickReward = (type) => {
        if (claimStatus === REQ_STATUS.LOADING) return;
        dispatch(reqFirstPayGiftClaim({ reward_type: type }));
    }

    const renderDayReward = (index) => {
        const mul = giftInfo.day_rewards.bonus[index] / 100
        const money = mul * giftInfo.pay_amount;
        return renderMoney(money.toFixed(2));
    }

    const getNumber = (num) => {
        return parseFloat(num.toFixed(2));
    }

    const rendePurchased = () => {
        return (
            <div className={styles.container}>
                <div className={styles.top_box}>
                    <div className={styles.title_lbl}>
                        YOU HAVE OBTAINED
                    </div>
                    <div className={`${styles.lbl_bonus} amount-yellow`}>Bonus ${giftInfo.total_bonus}</div>
                    <div className={styles.space_line}></div>
                    <div className={styles.des_box}>
                        <div className={styles.des_item}>
                            <LazyImage className={styles.icon} src={coinImg} alt={i18n.t("firstDeposit.tis_1")} />
                            <p>{i18n.t("firstDeposit.tis_1")}</p>
                        </div>

                        <div className={styles.des_item}>
                            <LazyImage className={styles.icon} src={coinImg} alt={i18n.t("firstDeposit.tis_2")} />
                            <p>{i18n.t("firstDeposit.tis_2")}</p>
                        </div>

                        <div className={styles.des_item}>
                            <LazyImage className={styles.icon} src={coinImg} alt={i18n.t("firstDeposit.tis_3")} />
                            <p>{i18n.t("firstDeposit.tis_3")}</p>
                        </div>
                    </div>
                </div>

                <div className={styles.scroll_box}>
                    <div className={styles.reward_tips}>
                        Congratulations! your deposit is successful!<br />
                        All bonuses will expire after <span className={styles.money}>
                            {expired_times.d} days at {`${expired_times.h}:${expired_times.m}:${expired_times.s}`},
                        </span><br />
                        please claim them on time
                    </div>

                    <RewardBox title={"Instant Credit"} >
                        <section>
                            {renderMoney(giftInfo.bonus_instantly)} will be credited<br />
                            immediately and automatically distributed to the game balance.
                        </section>
                    </RewardBox>

                    <RewardBox title={"7 Day Rewards"} type={RewardType.Day} state={giftInfo.day_rewards.status} onClick={onClickReward}>
                        <section>
                            From 2 to 7 days after deposit, you can receive an additional bonus of 20% of the deposit value, totaling {renderMoney(giftInfo.day_rewards.total_bonus)}.
                            <ul className={styles.ul_box}>
                                <li>On the second day, you can claim {renderDayReward(0)}.</li>
                                <li>On the third day, you can claim {renderDayReward(1)}.</li>
                                <li>On the fourth day, you can claim {renderDayReward(2)}.</li>
                                <li>On the fifth day, you can claim {renderDayReward(3)}.</li>
                                <li>On the sixth day, you can claim {renderDayReward(4)}.</li>
                                <li>On the seventh day, you can claim {renderDayReward(5)}.</li>
                            </ul>
                            Rewards can only be claimed on the same day and will become invalid once they expire
                        </section>
                    </RewardBox>

                    <RewardBox title={"Betting bonuses"} type={RewardType.Bonus} state={giftInfo.betting_bonus.status} onClick={onClickReward}>
                        <section>
                            After recharging, 50% of the deposit value will be allocated to the accumulated prize and you can receive
                            ${getNumber(giftInfo.betting_bonus.per_bet_bonus)} for every {getNumber(giftInfo.betting_bonus.per_bet)} bets.<br />
                            Your current total reward is {renderMoney(giftInfo.betting_bonus.total_bonus)}, you have already redeemed {renderMoney(giftInfo.betting_bonus.claimed_amount)},
                            you can still receive {renderMoney(giftInfo.betting_bonus.remaining_bonus)}
                            <br />
                            The value of your bet is <span className={styles.money}>{getNumber(giftInfo.betting_bonus.current_bet)}</span>,
                            you can redeem {renderMoney(giftInfo.betting_bonus.can_claim_amount)}
                        </section>
                    </RewardBox>

                    <RewardBox title={"Betting Tasks"} type={RewardType.Task} state={giftInfo.betting_task.status} onClick={onClickReward}>
                        <section>
                            After recharging, when your bet amount reaches {giftInfo.betting_task.bet_pay_times} times the deposit value,
                            you can receive a one-time reward of 80% of the deposit value.<br />
                            Your current total reward is {renderMoney(giftInfo.betting_task.total_bonus)},
                            your bet amount is <span className={styles.money}>{getNumber(giftInfo.betting_task.current_bet)}</span>,
                            you still need to bet <span className={styles.money}>{getNumber(giftInfo.betting_task.required_bet - giftInfo.betting_task.current_bet)}</span>
                        </section>
                    </RewardBox>

                    <div className={styles.space_line}></div>
                    {renderPsBox()}
                </div>
            </div>
        )
    }

    return (
        <>
            {
                has_purchased ? rendePurchased() : renderNotpurchase()
            }
        </>
    )
}

export default WFirstDeposit;