import { REQ_STATUS } from '@api/config';
import styles from './styles.module.scss';
import { getBonusStatus, getTurnplate } from "@features/turnplateSlice";
import WWithdrawalInfo from '@widgets/WWithdrawalInfo';
import { useDispatch, useSelector } from "react-redux";
import { reqTurnplateBonus } from '@features/api';
import WITHDRAW_TYPE from '@constants/withdraw_types';
import { getFreeWithdrawClaimStatus } from '@features/mainSlice';
import { useNavigate } from 'react-router';
import { ROUTE_PATH } from '@constants/routes';



const WReferral = () => {
    const turnplate = useSelector(getTurnplate);
    const bonusStatus = useSelector(getBonusStatus);
    const freeWithdrawStatus = useSelector(getFreeWithdrawClaimStatus);
    const dispatch = useDispatch();
    const navigate = useNavigate();

    if (!global.referralPayload) return <></>;

    const { type, score, callback } = global.referralPayload;
    const onConfirm = async () => {
        if (type == WITHDRAW_TYPE.SHARE) {
            if (bonusStatus === REQ_STATUS.LOADING) return;
            await dispatch(reqTurnplateBonus()).unwrap();
            navigate(ROUTE_PATH.HOME, { replace: true });
        } else if (type == WITHDRAW_TYPE.MISSION) {
            if (freeWithdrawStatus === REQ_STATUS.LOADING) return;
            callback && callback();
        }
    };


    if (type == WITHDRAW_TYPE.SHARE) {
        return (
            <div className={styles.container}>
                <span>${(turnplate?.collect_amount / global.CASH_BASE).toFixed(2)}</span>
                <WWithdrawalInfo
                    onConfirm={onConfirm}
                    loading={bonusStatus === REQ_STATUS.LOADING} />
            </div>
        );
    } else if (type == WITHDRAW_TYPE.MISSION) {
        return (
            <div className={styles.container}>
                <span>${(score).toFixed(2)}</span>
                <WWithdrawalInfo
                    onConfirm={onConfirm}
                    loading={freeWithdrawStatus === REQ_STATUS.LOADING} />
            </div>
        );
    } else {
        return <></>;
    }
};


export default WReferral;