import React, { useEffect, useState, useRef, Fragment, useCallback } from "react";
import Popup from "@components/Popup";
import styles from "./styles.module.scss";
import LazyImage from "@components/LazyImage";
import { useNavigate } from "react-router";
import { ROUTE_PATH } from "@constants/routes";
import { useWithdrawMission } from "@contexts/withdrawMissionContext";

import bg from "@assets/withdrawMission/bg.png";
import arrow from "@assets/withdrawMission/arrow.png";
import recordIcon from "@assets/withdrawMission/record.png";
import star from "@assets/withdrawMission/star.png";
import symbol from "@assets/withdrawMission/symbol.svg";


import { getBonusStatus, getMyRecord, getRecord, getTurnplate } from "@features/turnplateSlice";
import { Autoplay } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/react";
import styled from 'styled-components/macro';
import { useSelector } from "react-redux";
import Spring from "@components/Spring";
import { getFreeWithdraw, getFreeWithdrawClaimStatus, getFreeWithdrawMission, getUserInfo } from "@features/mainSlice";

import MISSION_TYPES from "@constants/mission_types";
import { REQ_STATUS } from "@api/config";
import SmallLoading from "@components/SmallLoading";
import useFreeWithdraw from "@hooks/useFreeWithdraw";
import { isFrequentTap } from "@utils/helpers";
const StyledSwiper = styled(Swiper)`
    height: 100%; /* 必须设置高度 */
    .swiper-wrapper {
        transition-timing-function: linear;
    }
`;


const i18n = global.i18n;

const WWithdrawMission = () => {
    const { open, setOpen } = useWithdrawMission();
    const withdrawInfo = useSelector(getUserInfo);
    const score = withdrawInfo.InsureScore;

    const record = useSelector(getRecord);
    // 只取前10条数据，避免过多DOM节点
    const displayRecords = record.slice(0, 10);
    const missions = useSelector(getFreeWithdrawMission);
    const claimStatus = useSelector(getFreeWithdrawClaimStatus);
    const { claimFreeWithdraw } = useFreeWithdraw();

    // const missions = {
    //     "stage1": {
    //         "stage": 1,
    //         "title": "阶段任务1",
    //         "reward": 10,
    //         "completed": false,
    //         "reward_status": 0,
    //         "reward_status_text": "不能领取",
    //         "can_claim": false,
    //         "tasks": [
    //             {
    //                 "id": "stage1_task1",
    //                 "title": "签到一次",
    //                 "type": "sign_in",
    //                 "completed": false,
    //                 "status": 0,
    //                 "status_text": "未完成",
    //                 "progress": 0,
    //                 "target": 1
    //             },
    //             {
    //                 "id": "stage1_task2",
    //                 "title": "下注金额达到100",
    //                 "type": "bet_amount",
    //                 "completed": false,
    //                 "status": 0,
    //                 "status_text": "未完成",
    //                 "progress": 0,
    //                 "target": 100
    //             },
    //             {
    //                 "id": "stage1_task3",
    //                 "title": "再充值一次",
    //                 "type": "recharge",
    //                 "completed": false,
    //                 "status": 0,
    //                 "status_text": "未完成",
    //                 "progress": "0",
    //                 "target": 1
    //             }
    //         ]
    //     },
    //     "stage2": {
    //         "stage": 2,
    //         "title": "阶段任务2",
    //         "reward": 10,
    //         "unlocked": false,
    //         "completed": false,
    //         "reward_status": 0,
    //         "reward_status_text": "不能领取",
    //         "can_claim": false,
    //         "tasks": [
    //             {
    //                 "id": "stage2_task1",
    //                 "title": "玩六款游戏",
    //                 "type": "play_games",
    //                 "completed": false,
    //                 "status": 0,
    //                 "status_text": "未完成",
    //                 "progress": 0,
    //                 "target": 6
    //             },
    //             {
    //                 "id": "stage2_task2",
    //                 "title": "下注金额达到3000",
    //                 "type": "bet_amount",
    //                 "completed": false,
    //                 "status": 0,
    //                 "status_text": "未完成",
    //                 "progress": 0,
    //                 "target": 3000
    //             },
    //             {
    //                 "id": "stage2_task3",
    //                 "title": "发起一次邀请",
    //                 "type": "invite",
    //                 "completed": false,
    //                 "status": 0,
    //                 "status_text": "未完成",
    //                 "progress": 0,
    //                 "target": 1
    //             }
    //         ]
    //     },
    //     "stage3": {
    //         "stage": 3,
    //         "title": "阶段任务3（循环任务）",
    //         "unlocked": false,
    //         "is_loop": true,
    //         "current_loop": 0,
    //         "tasks": [
    //             {
    //                 "id": "stage3_task1",
    //                 "title": "下注金额达到600",
    //                 "type": "bet_amount",
    //                 "reward": 20,
    //                 "completed": false,
    //                 "reward_status": 0,
    //                 "reward_status_text": "不能领取",
    //                 "can_claim": false,
    //                 "progress": 0,
    //                 "target": 600
    //             },
    //             {
    //                 "id": "stage3_task2",
    //                 "title": "下注金额达到1200",
    //                 "type": "bet_amount",
    //                 "reward": 40,
    //                 "completed": false,
    //                 "reward_status": 0,
    //                 "reward_status_text": "不能领取",
    //                 "can_claim": false,
    //                 "progress": 0,
    //                 "target": 1200
    //             }
    //         ]
    //     }
    // };


    const stageArr = [missions.stage1, missions.stage2, missions.stage3];
    const navigate = useNavigate();

    const [activeTab, setActiveTab] = useState(0);
    const tabRefs = useRef([]);
    const underlineRef = useRef(null);

    const [canRender, setCanRender] = useState(open);

    // const withdrawInfo = {"state": 1, "total": 40, "InsureScore": 10 };



    useEffect(() => {
        if (open) {
            setCanRender(true);
            let index = stageArr?.findIndex(stage => stage.reward_status != 2);
            if (activeTab != index && index != -1) setActiveTab(index);
        } else {
            setTimeout(() => {
                setCanRender(false);
            }, 200);
        }
    }, [open, missions]);

    const [refsReady, setRefsReady] = useState(false);

    // 使用 useCallback 避免不必要的重新创建
    const setTabRef = useCallback((index, el) => {
        tabRefs.current[index] = el;

        if (index != 2) return;

        // 检查是否所有 ref 都已设置
        const allReady = tabRefs.current.every(ref => ref !== null && ref !== undefined);
        if (allReady) {
            // console.error("allReady", allReady);
            setRefsReady(true);
        }
    }, []);

    // 更新下划线位置
    const updateUnderline = (index) => {
        const activeTabElement = tabRefs.current[index];
        if (activeTabElement && underlineRef.current) {
            const { offsetLeft, offsetWidth } = activeTabElement;

            // 定位到tab的中心点
            const tabCenter = offsetLeft + (offsetWidth / 2);

            underlineRef.current.style.left = `${tabCenter}px`;
            underlineRef.current.style.width = `4.93rem`;

            // 添加CSS类实现transform居中
            underlineRef.current.style.transform = 'translateX(-50%)';
        }
    };


    useEffect(() => {
        updateUnderline(activeTab);
    }, [activeTab, refsReady, canRender]);

    // 处理窗口大小变化 下划线
    useEffect(() => {
        const handleResize = () => updateUnderline(activeTab);
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, [activeTab]);

    const handleTabClick = (stage, index) => {
        if (index != 0 && !stage?.unlocked) {
            return;
        }
        // console.error("handleTabClick", index);
        setActiveTab(index);
    };


    const renderContent = () => {
        const data = stageArr[activeTab];
        console.error("renderContent data", data);
        const totalTask = data?.tasks.length;
        const completedTask = data?.tasks.filter(item => item.completed).length;

        const handleTaskGo = (type) => {
            let { link, target } = MISSION_TYPES[type];
            if (link) {
                navigate(link);
            } else if (target) {
                global[target] && global[target]();
            }
            setOpen(false);
            // console.error("handleTaskGo", link, target);
        };
        // console.error("stageArr data", data);
        // console.error("completedTask", completedTask);

        const renderTaskProgress = (item) => {
            let type = item?.type;
            if (type == "bet_amount") {
                return Math.trunc(item?.progress);
            } else {
                return item?.progress;
            }
        };
        return (
            <>
                {
                    data?.tasks.map((item, index) => {
                        if (activeTab === 2 && index > 0) return (<></>);

                        return (
                            <div className={`${styles.mission} ${styles.missionOver}`}>
                                <div className={styles.title}>
                                    {item?.title}
                                </div>
                                <div className={styles.bottom}>
                                    <div className={styles.progress}>
                                        <div
                                            className={styles.progressBar}
                                            style={{ width: `${item?.progress / item?.target * 100}%`, border: item?.progress == 0 ? "none" : 'border: 0.07rem solid rgba(30, 248, 181, 1)' }}
                                        />
                                        <span className={styles.progressText}>
                                            {renderTaskProgress(item)}/{item?.target}
                                        </span>
                                    </div>

                                    {
                                        !item?.completed ? (<div className={styles.go} onClick={() => handleTaskGo(item?.type)}>
                                            GO
                                        </div>) : (<svg className={styles.check} >
                                            <use xlinkHref={`${symbol}#check`} />
                                        </svg>)
                                    }

                                </div>
                            </div>
                        );
                    })
                }

                {
                    activeTab === 2 ? (<div className={styles.tipsAll}>
                        <div>Withdraw <span className={styles.money}>${data?.tasks[0].reward}</span> for each task you</div>
                        <div>complete.</div>
                        <div>This task can be repeated until</div>
                        <div>you withdraw all your Free</div>
                        <div>Bonus!</div>
                    </div>) : <></>
                }



                {
                    activeTab === 2 ? (
                        <>
                            {
                                data?.tasks[0]?.reward_status != 2 ? (
                                    <>
                                        <div className={`${styles.taskInfo} ${data?.completed ? styles.missionAllOver : ""}`} />

                                        {
                                            // 循环任务
                                            score < 20 ? <></> : (
                                                <div className={`${styles.withdrawBtn} ${data?.tasks[0]?.completed ? styles.canWithdraw : ""}`}
                                                    onClick={() => {
                                                        if (data?.tasks[0]?.completed) handleWithdrawClick();
                                                    }}
                                                >
                                                    {
                                                        claimStatus === REQ_STATUS.LOADING ? <SmallLoading fill="#ffff" /> : <span>Withdraw ${data?.tasks[0]?.reward} Now</span>
                                                    }

                                                </div>)


                                        }

                                        {
                                            score < 20 ? <></> : renderRecord()
                                        }

                                        {
                                            score < 20 ? <div className={`${styles.withdrawOverMask}`} /> : <></>
                                        }
                                    </>
                                ) : (
                                    <>
                                        <div className={`${styles.withdrawOverMask}`} />
                                        <div className={`${styles.taskInfoProcessed}`}>
                                            Withdrawal Processed
                                        </div>
                                    </>
                                )
                            }
                        </>
                    ) :
                        (
                            <>
                                {
                                    data?.reward_status < 2 ? (
                                        <>
                                            {
                                                <div className={`${styles.taskInfo} ${data?.completed ? styles.missionAllOver : ""}`}>
                                                    Task completed {completedTask}/{totalTask}
                                                </div>
                                            }

                                            {
                                                <div className={`${styles.withdrawBtn} ${data?.completed ? styles.canWithdraw : ""}`}
                                                    onClick={() => {
                                                        if (data?.completed) handleWithdrawClick();
                                                    }}
                                                >
                                                    {
                                                        claimStatus === REQ_STATUS.LOADING ? <SmallLoading fill="#ffff" /> : <span>Withdraw ${data?.reward} Now</span>
                                                    }
                                                </div>
                                            }

                                            {renderRecord()}
                                        </>
                                    ) : (
                                        <>
                                            <div className={`${styles.withdrawOverMask}`} />
                                            <div className={`${styles.taskInfoProcessed}`}>
                                                {
                                                    data?.reward_status == 2 ? "WithdrawalUnderBank Review-Please Wait" : "Withdrawal Processed"
                                                }
                                            </div>
                                        </>
                                    )
                                }
                            </>
                        )

                }


            </>
        );
    };

    const handleWithdrawClick = () => {
        if (claimStatus === REQ_STATUS.LOADING) return;
        if (isFrequentTap("wwithdraw_mission_claim", 1000)) return;

        const data = stageArr[activeTab];
        let reward = data?.reward;
        if (activeTab === 2) {
            reward = data?.tasks[0]?.reward;
        }
        claimFreeWithdraw(reward);
        if (open) setOpen(false);
    };

    const formatPhone = (phone) => {
        let tstr = phone.substring(1, phone.length - 2);
        phone = phone.replace(tstr, '*'.repeat(tstr.length));
        if (!phone.startsWith("55")) phone = "55" + phone;
        return phone;
    };

    const renderRecord = () => {

        return (
            <div className={styles.marquee_con}>
                <StyledSwiper
                    direction={"vertical"}
                    slidesPerView={1}
                    loop={true}
                    autoplay={{
                        delay: 2500,
                        disableOnInteraction: false,
                        pauseOnMouseEnter: true, // 鼠标悬停暂停
                        waitForTransition: false // 不等待过渡完成
                    }}
                    modules={[Autoplay]}
                    speed={600}
                    simulateTouch={false} // 禁用触摸
                    allowTouchMove={false} // 禁用触摸移动
                >
                    {displayRecords?.map((item, index) => (
                        <SwiperSlide key={index}>
                            <div className={styles.marquee_item}>
                                <span className={styles.avatar} />
                                <span className={styles.phone}>
                                    {formatPhone(item.phone)}
                                </span>
                                <span className={styles.tip} >
                                    Just withdraw
                                </span>
                            </div>
                        </SwiperSlide>
                    ))}
                </StyledSwiper>
            </div>
        );
    };

    const unlockStyle = (stage, index) => {
        if (index != 0 && !stage?.unlocked) {
            return styles.locked;
        } else {
            return "";
        }
    };

    const handleClickRecord = () => {
        // console.error("handleClickRecord");
        setOpen(false);
        navigate(ROUTE_PATH.FW_RECORD);
    };

    if (!canRender) return <></>;

    return (
        <>
            <div className={styles.mask} onClick={() => setOpen(false)} style={{ display: open ? 'block' : 'none' }} />

            <div className={`${styles.container} ${open ? styles.open : styles.close}`} >
                <div className={styles.header} >
                    <img src={bg} alt="" className={styles.imgBg} />
                    <img src={arrow} alt="" className={styles.arrow} onClick={() => setOpen(false)} />
                    <img src={recordIcon} alt="" className={styles.record} onClick={handleClickRecord} />
                    <div className={styles.freeBonus}>
                        <img src={star} alt="" />
                        <span>{withdrawInfo.InsureScore}</span>
                    </div>

                    <div className={styles.tips}>
                        Complete the task to withdraw all bonuses
                    </div>

                    <div className={styles.tabs}>
                        <div ref={underlineRef} className={styles.tabUnderline} />
                        {
                            stageArr?.map((stage, index) => (
                                <Fragment key={index} >
                                    <div
                                        // ref={el =>
                                        //     tabRefs.current[index] = el
                                        // }
                                        ref={el => setTabRef(index, el)}
                                        className={`${styles.tab} ${activeTab === index ? styles.activeTab : ''} ${unlockStyle(stage, index)}`}
                                        onClick={() => handleTabClick(stage, index)}
                                    >
                                        {
                                            !stage?.is_loop ? `Withdraw $${stage.reward}` : `Withdraw all`
                                        }
                                    </div>
                                    {
                                        index < stageArr.length - 1 && (
                                            <span className={`${activeTab === index ? styles.activeTab : ''}`}>&gt;</span>
                                        )
                                    }
                                </Fragment>
                            ))
                        }
                    </div>

                </div>

                <div className={styles.content}>
                    {
                        renderContent()
                    }
                </div>
            </div>
        </>
    );

};
export default WWithdrawMission;