import Popup from '@components/Popup';
import styles from './styles.module.scss';
import bg from "@assets/come_back/bg.webp";
import icon_plane from "@assets/come_back/icon_plane.webp";

import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router';
import { ROUTE_PATH } from '@constants/routes';
import { useThemeProvider } from '@contexts/themeContext';
import { useSelector } from 'react-redux';
import { getFreeWithdraw } from '@features/mainSlice';

const WComeBackWithdraw = () => {
    const { openRecommandGame } = useThemeProvider();
    const [isShow, setIsShow] = useState(false);
    const navigate = useNavigate();

    const withdrawInfo = useSelector(getFreeWithdraw)
    const [progress, setProgress] = useState(0);

    useEffect(() => {
        if (withdrawInfo && withdrawInfo.total > 0) {
            const value = Math.floor(withdrawInfo.InsureScore / withdrawInfo.total);
            setProgress(value * 100);
        }
    }, [withdrawInfo]);

    const show = () => {
        setIsShow(true);
    }

    const hide = () => {
        setIsShow(false);
    }

    const handleCloseClick = () => {
        hide();
        global.openNextPopup();
    }

    const handlePlayClick = () => {
        openRecommandGame();
        global.clearPopupFlow();
        hide();
    }

    const handleDepositClick = () => {
        navigate(ROUTE_PATH.DEPOSIT);
        global.clearPopupFlow();
        hide();
    }

    const getNeedMoney = () => {
        if (!withdrawInfo) return 0;
        const value = withdrawInfo.InsureScore - withdrawInfo.total;
        return Number(value.toFixed(2));
    }

    useEffect(() => {
        const comebackWithdraw = {
            show, hide
        }
        global.comebackWithdraw = comebackWithdraw;
    }, [])


    return (
        <Popup onClose={handleCloseClick} open={isShow} popupBg={bg}>
            <div className={styles.container}>
                <span>
                    Your Balance <span className={styles.money}>${withdrawInfo?.InsureScore}</span>
                </span>
                <div className={styles.content}>
                    <span>You just need <span className={styles.money}>${getNeedMoney()}</span></span>
                    <span>more to withdraw</span>
                </div>
                <div className={styles.progress}>
                    <div style={{ width: `${progress}%` }}>
                        <img src={icon_plane} />
                    </div>
                    <span>{`${withdrawInfo.InsureScore} / ${withdrawInfo.total}`} Withdraw</span>
                </div>
                <button className='button-green2' onClick={handlePlayClick}>
                    {/* <SmallLoading fill='#fff' /> */}
                    Play to win
                </button>

                <button onClick={handleDepositClick}>Deposit</button>
            </div>
        </Popup >

    )
}

export default WComeBackWithdraw;