import showAlert from "@/components/basic/Alert"
import { View, Text } from "@tarojs/components";
import './CheckAccess.scss'

import { memo, useContext, useEffect, useState } from "react";
import { TimeFormatter } from "@/utils/time_format";
import { useDispatch, useSelector } from "react-redux";
import { getPlans, setPlan } from "@/services/trackTimeDuration";
import { chooseMode, initTarget, updateStep } from "@/store/set_target";
import { jumpPage } from "../hooks/Common";
import { useDidHide, useDidShow } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { useTranslation } from "react-i18next";
import { kIsIOS } from "@/utils/tools";
import { ColorType } from "@/context/themes/color";
// import { useIsFocused } from "@react-navigation/native";

let confirmAction: any = null;
let cancelAction: any = null;
let timer;
let access;
let useNavigation, AppState, Modal, useIsFocused;
if (process.env.TARO_ENV == 'rn') {
    AppState = require("react-native").AppState
    Modal = require("react-native").Modal
    useNavigation = require("@react-navigation/native").useNavigation
    useIsFocused = require("@react-navigation/native").useIsFocused
}

const CheckAccess = memo((props: { record: any, count: number, access: any }) => {
    // export default function CheckAccess(props: { record: any, count: number }) {
    const [showFastAlert, setShowFastAlert] = useState(false)
    const [alertTitle, setAlertTitle] = useState('')
    const [alertContent, setAlertContent] = useState('')
    const [showCancel, setShowCancel] = useState(false)
    const [keepContent, setKeepContent] = useState(false)
    const [cancelText, setCancelText] = useState('')
    const [confirmText, setConfirmText] = useState('')
    const [subConfirmText, setSubConfirmText] = useState('')
    const user = useSelector((state: any) => state.user);
    const { t } = useTranslation()

    //判断选择混合场景，如果成功了，就弹窗
    const [checkChooseMixed, setCheckChooseMixed] = useState(false)
    const [chooseMixedSuccess, setChooseMixedSuccess] = useState(false)

    const ring = useSelector((state: any) => state.ring);
    const dispatch = useDispatch();

    let navigation;
    let isFocused = false;
    if (useNavigation) {
        navigation = useNavigation()
        isFocused = useIsFocused()
    }



    useEffect(() => {
        var obj = props.record
        if (props.access) {
            const member_expire = props.access.member.expire
            const member_status = props.access.member.status
            if (member_expire && new Date().getTime() > member_expire && member_status && member_status=='MEMBER') {
                if (global.indexPageRefresh) {
                    global.indexPageRefresh()
                }
            }

            if (!user.test_user) {
                return
            }
            if (!global.memberAlert) {
                return;
            }
            global.ring = ring;
            const currentStatus = props.access.fast_sleep.current.qualification.status
            const preStatus = props.access.fast_sleep.previous.qualification.status
            if ((preStatus == 'PROVISIONAL_QUALIFIED' || preStatus == 'QUALIFIED_UNTIL_EXPIRE') &&
                currentStatus == 'PENDING' &&
                // global.ring.current_record.scenario != 'FAST' &&
                obj.current_record.status == 'WAIT_FOR_START') {
                loseGain(props.access.fast_sleep)
            }
            // else if ((preStatus == 'PROVISIONAL_QUALIFIED' || preStatus == 'QUALIFIED_UNTIL_EXPIRE') &&
            //     currentStatus == 'NOT_QUALIFIED' &&
            //     global.ring.current_record.scenario == 'FAST_SLEEP' &&
            //     obj.current_record.status == 'WAIT_FOR_START') {
            //     loseGain(props.access.fast_sleep)
            // }
            else if (currentStatus == 'PROVISIONAL_QUALIFIED') {
                Taro.setStorage({ key: 'showedDisqualifiedAlert', data: false })
                const { fast_expire, sleep_expire } = props.access.fast_sleep.current.qualification
                if (fast_expire && new Date().getTime() > fast_expire && obj.current_record.status == 'WAIT_FOR_START') {
                    if (global.indexPageRefresh) {
                        global.indexPageRefresh()
                    }
                }
                if (sleep_expire && new Date().getTime() > sleep_expire && obj.current_record.status == 'WAIT_FOR_START') {
                    if (global.indexPageRefresh) {
                        global.indexPageRefresh()
                    }
                }

            }
            else if (currentStatus == 'QUALIFIED_UNTIL_EXPIRE') {

                Taro.setStorage({ key: 'showedDisqualifiedAlert', data: false })
                const member_expire = props.access.member.expire
                if (member_expire && new Date().getTime() > member_expire) {
                    if (global.indexPageRefresh) {
                        global.indexPageRefresh()
                    }
                }
                // if (member_expire && new Date().getTime() > member_expire && obj.current_record.status == 'WAIT_FOR_START' &&
                //     global.ring.current_record.scenario != 'FAST') {
                //     if (global.indexPageRefresh) {
                //         global.indexPageRefresh()
                //     }
                // }
            }

            if (obj.current_record.status != 'WAIT_FOR_START') {
                Taro.setStorage({ key: 'showedDisqualifiedAlert', data: false })
            }
        }
    }, [props.count])

    // const handleAppStateChange = (nextAppState) => {
    //     console.log(nextAppState)
    //     if (nextAppState != 'active') {
    //         return
    //     }
    // };

    function viewWillAppear() {
        if (checkChooseMixed && chooseMixedSuccess) {
            upgradeSuccess()
            confirmAction = null
        }
        setCheckChooseMixed(false)
        setChooseMixedSuccess(false)
    }

    function viewWillDisappear() {
    }

    // useDidShow(() => {
    //     console.log('user did show');
    //     viewWillAppear()
    // })

    useEffect(() => {
        if (process.env.TARO_ENV == 'rn') {
            // AppState.addEventListener('change', handleAppStateChange);
            navigation.addListener('focus', () => {
                viewWillAppear()
            });

            // 当页面即将消失时执行
            navigation.addListener('blur', () => {
                viewWillDisappear()
            });

        }

        global.chooseMixed = () => {
            setChooseMixedSuccess(true)
            setShowFastAlert(false)
            setKeepContent(false)
        }

        global.paySuccess = (res) => {
            cancelAction = null
            confirmAction = null
            setShowFastAlert(false)
            setKeepContent(false)
            setTimeout(() => {
                global.refreshAccess(res)
            }, 2000)

        }
        global.checkAccess = (acccessData: any) => {
            debugger
            if (!user.test_user) {
                return
            }
            if (!global.memberAlert) {
                return;
            }
            const currentStatus = acccessData.current.qualification.status
            const preStatus = acccessData.previous.qualification.status
            access = acccessData


            setSubConfirmText('')
            confirmAction = null

            const { trigger_event } = access.current.qualification;

            //删除记录后仍有资格，不做特殊处理。只有删除时为NOT_SATISFIED_AFTER_DELETE时，弹失去资格弹窗
            if (trigger_event == 'SATISFIED_AFTER_DELETE') {
                return;
            }


            if (preStatus == 'NOT_QUALIFIED' && currentStatus == 'NOT_QUALIFIED') {
                const { streak_fast_current, streak_fast_min_required } = acccessData.current.qualification.condition
                if (streak_fast_current == 0) {
                    return;
                }
                setShowFastAlert(true)
                setKeepContent(false)
                setAlertTitle(t('feature.check_access.non_access.title'))
                setAlertContent(t('feature.check_access.non_access.desc',
                    {
                        day: streak_fast_current,
                        // day_left: streak_fast_min_required - streak_fast_current,
                        // day_unit: streak_fast_min_required - streak_fast_current == 1 ? 'day' : 'days'
                    }))
                setShowCancel(false)
                setConfirmText(t('feature.check_access.non_access.btn'))
            }
            else if (preStatus == 'NOT_QUALIFIED' && (currentStatus == 'PROVISIONAL_QUALIFIED' || currentStatus == 'QUALIFIED_UNTIL_EXPIRE') && global.ring.current_record.scenario != 'FAST_SLEEP') {

                const { streak_fast_current } = acccessData.current.qualification.condition
                const reason = t('feature.check_access.gain_access.reason', { day: streak_fast_current })
                Taro.setStorage({ key: 'showedDisqualifiedAlert', data: false })
                var expire = acccessData.current.qualification.fast_expire
                setShowFastAlert(true)
                setKeepContent(true)
                setAlertTitle(t('feature.check_access.gain_access.title'))
                setAlertContent(t('feature.check_access.gain_access.desc', { reason: reason }))
                setShowCancel(true)
                setCancelText(t('feature.check_access.gain_access.stay_btn'))
                setConfirmText(t('feature.check_access.gain_access.upgrade'))
                setSubConfirmText(t('feature.check_access.gain_access.upgrade_desc', { time: TimeFormatter.countdown(expire) }))

                confirmAction = upgrade

                // if (process.env.TARO_ENV=='rn' && !kIsIOS){
                //     return
                // }

                timer = setInterval(() => {
                    if (new Date().getTime() > expire) {
                        cancel()
                        return
                    }
                    setSubConfirmText(t('feature.check_access.gain_access.upgrade_desc', { time: TimeFormatter.countdown(expire) }))
                    // setConfirmText(`Upgrade to Fasting with Sleep\n(Offer Expiring in ${TimeFormatter.countdown(expire)})`)
                }, 1000)
            }
            else if ((preStatus == 'PROVISIONAL_QUALIFIED' || preStatus == 'QUALIFIED_UNTIL_EXPIRE') && (currentStatus == 'PROVISIONAL_QUALIFIED' || currentStatus == 'QUALIFIED_UNTIL_EXPIRE')) {
                const { streak_fast_current, streak_sleep_current } = acccessData.current.qualification.condition
                if (global.ring.current_record.scenario == 'FAST') {
                    var expire = acccessData.current.qualification.fast_expire
                    const reason = t('feature.check_access.gain_access.reason', { day: streak_fast_current })
                    setShowFastAlert(true)
                    // setKeepContent(false)
                    setKeepContent(true)
                    setAlertTitle(t('feature.check_access.gain_access.title'))
                    setAlertContent(t('feature.check_access.gain_access.desc', { reason: reason }))
                    setShowCancel(true)
                    setCancelText(t('feature.check_access.gain_access.stay_btn'))
                    setConfirmText(t('feature.check_access.gain_access.upgrade'))
                    setSubConfirmText(t('feature.check_access.gain_access.upgrade_desc', { time: TimeFormatter.countdown(expire) }))
                    confirmAction = upgrade
                    timer = setInterval(() => {
                        if (new Date().getTime() > expire) {
                            cancel()
                            return
                        }
                        setSubConfirmText(t('feature.check_access.gain_access.upgrade_desc', { time: TimeFormatter.countdown(expire) }))
                        // setConfirmText(`Upgrade to Fasting with Sleep\n(Offer Expiring in ${TimeFormatter.countdown(expire)})`)
                    }, 1000)
                    return;
                }

                setKeepContent(false)
                setShowFastAlert(true)
                setAlertTitle(t('feature.check_access.stay_qualified.title'))
                setAlertContent(t('feature.check_access.stay_qualified.desc', { fast_streak_day: streak_fast_current, sleep_streak_day: streak_sleep_current }))
                setShowCancel(false)
                setConfirmText(t('feature.check_access.stay_qualified.btn'))
            }
            else if ((preStatus == 'QUALIFIED_UNTIL_EXPIRE' || preStatus == 'PROVISIONAL_QUALIFIED')
                && currentStatus == 'PENDING'
                // && global.ring.current_record.scenario == 'FAST_SLEEP'
            ) {
                loseGain(acccessData);
            }
            // else if ((preStatus == 'QUALIFIED_UNTIL_EXPIRE' || preStatus == 'PROVISIONAL_QUALIFIED')
            //     && currentStatus == 'NOT_QUALIFIED'
            //     && global.ring.current_record.scenario == 'FAST_SLEEP'
            // ) {
            //     loseGain(acccessData);
            // }
        }
    }, [])

    function upgradeSuccess() {
        setShowFastAlert(false)
    }



    async function loseGain(access) {
        var showedDisqualifiedAlert = await getStorage('showedDisqualifiedAlert') || false;
        if (showedDisqualifiedAlert) {
            return;
        }
        if (timer) {
            clearInterval(timer)
            timer = null
        }

        var desc = ''
        const { trigger_event, fast_expire, sleep_expire, condition } = access.current.qualification;
        var dt = fast_expire;
        if (sleep_expire && sleep_expire < fast_expire) {
            dt = sleep_expire
        }
        var date = TimeFormatter.getMonthAndDayByTimestamp(dt, true)
        var day_unit = Math.max(condition.streak_fast_min_required - 1, 1) == 1 ? 'day' : 'days';

        switch (trigger_event) {
            case 'FAST_STREAK_LOST':
                desc = t('feature.check_access.lost_reason.fast_streak_lost');
                break;
            case 'SLEEP_STREAK_LOST':
                desc = t('feature.check_access.lost_reason.sleep_streak_lost');
                break;
            case 'FAST_SLEEP_STREAKS_LOST':
                desc = t('feature.check_access.lost_reason.fast_sleep_streaks_lost');
                break;
            case 'SLEEP_STREAK_NOT_GROWING':
                desc = t('feature.check_access.lost_reason.sleep_streak_not_growing');
                break;
            case 'NOT_SATISFIED_AFTER_DELETE':
                desc = t('feature.check_access.lost_reason.not_satisfied_after_delete', { day: Math.max(condition.streak_fast_min_required - 1, 1), day_unit: day_unit });
                break;
            case 'NA':
            default:
                break;
        }

        // console.error('失去资格弹窗', trigger_event, desc);


        setShowFastAlert(true)
        setKeepContent(true)
        setAlertTitle(t('feature.check_access.lose_access.title'))
        setAlertContent(t('feature.check_access.lose_access.desc', { reason: desc, require_days: condition.streak_fast_min_required }))
        setShowCancel(true)
        setCancelText(t('feature.check_access.lose_access.btn'))
        setConfirmText('Become a PRO member')
        setSubConfirmText('')
        setTimeout(() => {
            cancelAction = changeFastScenaria
            confirmAction = pay
        }, 100)
        // confirmAction = pay
        // cancelAction = changeFastScenaria
        Taro.setStorage({ key: 'showedDisqualifiedAlert', data: true })

        // changeFastScenaria()
    }

    function changeFastScenaria() {
        cancelAction = null
        confirmAction = null
        const { start_time, end_time } = global.ring.schedule.fast
        var params: any = {
            scenario: 'FAST',
            trigger_event: 'POPUP_PENDING_SUBSCRIBE_FAIL',
            method: 'USER_SET',
            schedule: {
                fast: {
                    start_time: start_time,
                    end_time: end_time,
                },
            }
        }
        setPlan(params).then(res => {
            if (global.indexPageRefresh) {
                global.indexPageRefresh()
            }
        })
    }

    async function getStorage(key: string) {
        try {
            const res = await Taro.getStorage({ key });
            return res.data;
        } catch {
            return '';
        }
    }



    function upgrade() {
        const { prev_input, valid, start_time, end_time } = global.ring.schedule.sleep
        if (prev_input && valid) {
            setShowFastAlert(true)
            setKeepContent(true)
            setAlertTitle(t('feature.check_access.sleep_schedule.title'))
            setAlertContent(t('feature.check_access.sleep_schedule.desc',
                { start_time: start_time, end_time: end_time }))
            setShowCancel(true)
            setCancelText(t('feature.check_access.sleep_schedule.cancel'))
            setConfirmText(t('feature.check_access.sleep_schedule.confirm'))
            setSubConfirmText('')
            setTimeout(() => {
                cancelAction = cancelSetting
                confirmAction = goSetting
            }, 100)
        }
        else {
            goSetting()
        }
        // const { expire } = access.current.qualification
        // setShowFastAlert(true)
        // setAlertTitle('Congrats on Your PRO Status!')
        // setAlertContent(`To preserve this status, continue your fasting streak in ${TimeFormatter.countdown(expire)} and begin your sleep streak. Remember to keep both of them going.`)
        // setShowCancel(false)
        // setConfirmText(`I got this!`)
        // timer = setInterval(() => {
        //     if (new Date().getTime() > expire) {
        //         cancel()
        //         return
        //     }
        //     setAlertContent(`To preserve this status, continue your fasting streak in ${TimeFormatter.countdown(expire)} and begin your sleep streak. Remember to keep both of them going.`)
        // }, 1000)
    }

    function goSetting() {

        getPlans().then(res => {
            const data = res as { scenarios: any[] };
            console.log(data)
            var targets: any = {}
            data.scenarios.forEach((item) => {
                if (item.name == 'FAST') {

                    if (item.schedule.fast.duration.prev_input) {
                        item.schedule.fast.duration.last_value = item.schedule.fast.duration.init_value
                    }
                    targets.fast = item
                }
                else if (item.name == 'SLEEP') {
                    targets.sleep = item
                }
            })
            dispatch(initTarget(targets))
            dispatch(updateStep({ step: 2 }))
            dispatch(chooseMode({ isMixed: true }))
            setCheckChooseMixed(true)
            jumpPage(`/pages/clock/SetGoal?upgrade=true&isSelf=1&trigger_event=POPUP_QUALIFIED_UPGRADED_SET`, 'SetGoal', navigation, {
                upgrade: true,
                isSelf: 1,
                trigger_event: 'POPUP_QUALIFIED_UPGRADED_SET'

            })
            confirmAction = goSetting
        })

    }

    function pay() {
        jumpPage('', 'ProductList', navigation)
        setTimeout(() => {
            confirmAction = pay
            cancelAction = changeFastScenaria
        }, 200)
    }

    function cancelSetting() {
        const { start_time, end_time } = global.ring.schedule.fast
        var params: any = {
            scenario: 'FAST_SLEEP',
            method: 'USER_SET',
            trigger_event: 'POPUP_QUALIFIED_UPGRADED_DISMISS',
            schedule: {
                fast: {
                    start_time: start_time,
                    end_time: end_time,
                },
                sleep: {
                    start_time: global.ring.schedule.sleep.start_time,
                    end_time: global.ring.schedule.sleep.end_time,
                }
            }
        }
        setPlan(params).then(res => {
            if (global.indexPageRefresh) {
                global.indexPageRefresh()
            }
            upgradeSuccess()
        })
    }

    function confirm() {
        if (!keepContent) {
            setShowFastAlert(false)

        }

        if (timer) {
            clearInterval(timer)
            timer = null
        }
        if (confirmAction) confirmAction()
        confirmAction = null;
    }

    function cancel() {
        setShowFastAlert(false)
        confirmAction = null;
        if (timer) {
            clearInterval(timer)
            timer = null
        }
        if (cancelAction) cancelAction()
        cancelAction = null;
    }

    function alertPop() {
        return <View className="fast_alert_container">
            <View className="fast_alert_content" catchMove>
                <View className="fast_alert_title">{alertTitle}</View>
                <View className="fast_alert_detail">{alertContent}</View>
                <View className={subConfirmText.length > 0 ? 'fast_alert_confirm confirm_multline' : 'fast_alert_confirm'} onClick={confirm}>
                    <Text style={{ fontWeight: 'bold', color: ColorType.black }}>{confirmText}</Text>
                    {
                        subConfirmText.length > 0 && <Text className="confirm_sub_text">{subConfirmText}</Text>
                    }
                </View>
                {
                    showCancel && <View className="fast_alert_cancel" onClick={cancel}>{cancelText}</View>
                }
                {
                    user.test_user && global.memberAlert && <View style={{ display: 'flex', flexDirection: 'column' }}>
                        <Text style={{ color: '#fff', fontSize: 12 }}>member status:{props.access.member.status}</Text>
                        <Text style={{ color: '#fff', fontSize: 12 }}>current status:{props.access.fast_sleep.current.qualification.status}</Text>
                        <Text style={{ color: '#fff', fontSize: 12 }}>previous status:{props.access.fast_sleep.previous.qualification.status}</Text>
                        <Text style={{ color: '#fff', fontSize: 12 }}>trigger event:{props.access.fast_sleep.current.qualification.trigger_event}</Text>
                        <Text style={{ color: '#fff', fontSize: 12 }}>lost_access_total:{props.access.fast_sleep.current.qualification.condition.lost_access_total}</Text>
                        <Text style={{ color: '#fff', fontSize: 12 }}>streak_fast_min_required:{props.access.fast_sleep.current.qualification.condition.streak_fast_min_required}</Text>
                    </View>
                }


            </View>
        </View>
    }
    return <View>
        {
            user.test_user && global.memberAlert && showFastAlert && process.env.TARO_ENV == 'weapp' && alertPop()
        }
        {
            user.test_user && global.memberAlert && showFastAlert && isFocused && process.env.TARO_ENV == 'rn' && <Modal transparent={true}>
                <View style={{ backgroundColor: 'rgba(0,0,0,0.95)', width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center' }}>
                    {alertPop()}
                </View>
            </Modal>
        }
    </View>
})

export default CheckAccess;