
import { View, Text, PickerView,ScrollView } from "@tarojs/components";
import { useEffect, useRef, useState } from "react";
import { TimeFormatter } from "@/utils/time_format";
import { useDispatch, useSelector } from "react-redux";
import Taro from "@tarojs/taro";
import LimitPickers from '@/components/input/LimitPickers';
import { endFast, endSleep, startFast, startSleep } from "../actions/TrackTimeActions";
import { durationDatas, durationIndex, getColor, getDurationTitle, getTimePickerTitle, getTitle, textAlpha, textNextStepAlpha } from "../hooks/Console";
import PickerViews from "@/components/input/PickerViews";
import Modal from "@/components/layout/Modal";
import Stepper from "@/components/input/Stepper";
import { EndFastBtn, EndSleepBtn, StartFastBtn, StartSleepBtn } from "@/features/common/SpecBtns";
import Box from "@/components/layout/Box";
import './Console.scss'
import { ConsoleType, changeConsoleStatus } from "@/store/console";
import { updateScenario } from "@/store/time";
import { useTranslation } from "react-i18next";
import { ColorType } from "@/context/themes/color";
import { jumpPage } from "../hooks/Common";

let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function Component(props: { isNextStep?: boolean }) {
    const scenario = useSelector((state: any) => state.scenario);
    const time = useSelector((state: any) => state.time);
    const user = useSelector((state: any) => state.user);
    const common = useSelector((state: any) => state.common);
    const [isFast, setIsFast] = useState(true);
    const [fastDuration, setFastDuration] = useState<number>(0);
    const [sleepDuration, setSleepDuration] = useState<number>(0);

    const [fastPickerValue, setFastPickerValue] = useState([0, 0])
    const [sleepPickerValue, setSleepPickerValue] = useState([0, 0])
    const [isLoaded, setIsLoaded] = useState(false)
    const [showPageContainer,setShowPageContainer] = useState(false)
    const limitPickerRef = useRef(null)
    const durationPickerRef = useRef(null)
    const { t } = useTranslation()
    const dispatch = useDispatch();

    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        getStateDetail();
    }, [time.fast, time.sleep, time.status, time.scenario]);

    function getStateDetail() {
        if (time.fast) {
            var fastCount = time.fast.target_end_time - time.fast.target_start_time
            setFastDuration(fastCount)
            setFastPickerValue(durationIndex(time.fast.target_start_time, time.fast.target_end_time, common))
        }

        if (time.sleep) {
            var sleepCount = time.sleep.target_end_time - time.sleep.target_start_time
            setSleepDuration(sleepCount)
            setSleepPickerValue(durationIndex(time.sleep.target_start_time, time.sleep.target_end_time, common))
        }
        checkFastStatus()

    }

    function checkFastStatus() {
        if (time.scenario == 'FAST') {
            setIsFast(true)
        }
        else if (time.scenario == 'SLEEP') {
            setIsFast(false)
        }
        else {
            if (time.status == 'WAIT_FOR_START' || time.status == 'ONGOING3') {
                setIsFast(true)
            }
            else {
                setIsFast(false)
            }
        }
        setIsLoaded(true)
    }


    function showPicker() {
        // setShowPageContainer(true)
        // return
        if (global.testInfotimer) {
            return
        }
        global.set_time = new Date().getTime()
        updateNodeInfo()
        if (!global.isDebug) {
            return
        }
        global.testInfotimer = setInterval(() => {
            updateNodeInfo()

        }, 1000)

    }

    function pageContainerDetail(){
        return layoutContent()
    }

    function updateNodeInfo() {
        // var node = (<Modal testInfo={testLayout()} children={layoutContent()} dismiss={() => {
        //     global.showClockModal(false, null);
        //     hidePicker()
        // }} confirm={() => {
        //     hidePicker()
        //     var picker = limitPickerRef.current;
        //     pickerConfirm((picker as any).getConfirmData());
        //     global.showClockModal(false, null);
        // }} />);
        // global.showClockModal(true, node);
        var node = layoutContent()
        global.showClockModal(true, node,testLayout());
    }

    function hidePicker() {
        var node = layoutContent()
        global.showClockModal(false, node,null);
        if (global.testInfotimer) {
            clearInterval(global.testInfotimer)
            global.testInfotimer = null
        }
        else {
            console.log('global test info timer')
        }
    }

    function testLayout() {
        if (!user.test_user) {
            return <View />
        }
        if (!global.isDebug) {
            return <View />
        }
        var isStart = false;
        if (time.status == 'WAIT_FOR_START' || time.status == 'ONGOING1') {
            isStart = true
        }
        var isFast = false;
        switch (time.status) {
            case 'WAIT_FOR_START':
            case 'ONGOING':
                {
                    isFast = (scenario.name == 'FAST' || scenario.name == 'FAST_SLEEP')
                }
                break;
            case 'ONGOING1':
            case 'ONGOING2':
                {
                    isFast = false;
                }
                break
            case 'ONGOING3':
                {
                    isFast = true;
                }
                break;
        }

        if (props.isNextStep) {
            isFast = true
            isStart = false
        }

        return <ScrollView scrollY>
            <View style={{ color: '#fff',  paddingLeft: 30, display: 'flex', flexDirection: 'column' }}>
            <Text>check scenario:{isFast ? 'fast' : 'sleep'}</Text>
            <Text>check type:{isStart ? 'start' : 'end'}</Text>
            <Text style={{ marginTop: 10 }}>picker restriction</Text>
            <Text style={{ marginLeft: 50 }}>min:{TimeFormatter.formatTimestamp(global.limit)}</Text>
            <Text style={{ marginLeft: 50 }}>pick:{TimeFormatter.formatTimestamp(global.picker_time)}</Text>
            <Text style={{ marginLeft: 50 }}>max{TimeFormatter.formatTimestamp(global.set_time)}</Text>
            <Text style={{ marginTop: 10 }}>now:{TimeFormatter.formatTimestamp(new Date().getTime())}</Text>
            <Text>elapsed:{TimeFormatter.calculateTimeDifference(global.picker_time, new Date().getTime())}</Text>
            <Text style={{ marginTop: 10 }}>real start:{isStart ? '-' : TimeFormatter.formatTimestamp(isFast ? time.fast.real_start_time : time.sleep.real_start_time)}</Text>
            <Text>real duration:{isStart ? '-' : TimeFormatter.calculateTimeDifference(isFast ? time.fast.real_start_time : time.sleep.real_start_time, new Date().getTime())}</Text>
        </View>
        </ScrollView>
    }


    function layoutContent() {
        var limit = global.set_time - 7 * 3600 * 1000 * 24;
        global.limit = limit

        if (time.last_real_check_time) {
            limit = time.last_real_check_time
            global.limit = limit
            //当set_time秒数<=latest_record_time秒数时,最小限制时间戳需+1分钟
            if (new Date(global.set_time).getSeconds() <= new Date(time.last_real_check_time).getSeconds() && global.set_time-time.last_real_check_time>60000) {
                debugger
                limit = limit + 60 * 1000
            }
        }

        var title = getTimePickerTitle(time, t)
        var color = getColor(time)
        if (props.isNextStep) {
            title = t('feature.track_time_duration.console.fast_end')
            color = global.fastColor ? global.fastColor : ColorType.fast
        }


        return <View className="modal_content">
            <LimitPickers ref={limitPickerRef} limit={limit} limitDay={8}
            themeColor={color}
            title={title}
            onCancel={hidePicker} onChange={(e) => {
                pickerConfirm(e)
                hidePicker()
            }} />
        </View>
    }

    function pickerConfirm(t: number) {
        var date = new Date(t)
        var setDate = new Date(global.set_time);
        date.setMilliseconds(setDate.getMilliseconds());
        date.setSeconds(setDate.getSeconds());

        t = date.getTime();

        if (props.isNextStep) {
            endFast(t)
            return;
        }

        global.postBtnUpdateStatus('normal');

        if (isFast) {
            if (time.status == 'WAIT_FOR_START') {
                startFast(t, fastDuration).then(res => {

                    if ((res as any).current_record.scenario == 'FAST_SLEEP' &&
                        (res as any).current_record.status == 'ONGOING1') {
                        global.consoleType = 'going'
                        global.showSingleFastEnd()
                        dispatch(changeConsoleStatus({ status: ConsoleType.going }));
                    }
                    dispatch(updateScenario((res as any).current_record));
                    global.postBtnUpdateStatus('idle');
                });
            }
            else {
                endFast(t).then(res => {
                    dispatch(updateScenario((res as any).current_record));
                    global.postBtnUpdateStatus('idle');
                })
            }
        }
        else {
            if (time.status == 'WAIT_FOR_START' || time.status == 'ONGOING1') {
                startSleep(t, sleepDuration).then(res => {
                    dispatch(updateScenario((res as any).current_record));
                    global.postBtnUpdateStatus('idle');
                });
            }
            else {
                endSleep(t).then(res => {
                    dispatch(updateScenario((res as any).current_record));
                    global.postBtnUpdateStatus('idle');
                })
            }
        }
    }

    function mixedBtns() {
        return <View className="btn_bg">
            {
                (time.status == 'WAIT_FOR_START' || time.status == 'DONE') &&
                <StartFastBtn onClick={showPicker} />
            }
            {
                (time.status == 'ONGOING' || time.status == 'ONGOING3') &&
                <EndFastBtn onClick={showPicker} lowLight={time.fast.target_end_time > new Date().getTime()} />
            }
            {
                time.status == 'ONGOING1' && <StartSleepBtn onClick={showPicker} />
            }
            {
                time.status == 'ONGOING2' && <EndSleepBtn onClick={showPicker} lowLight={time.sleep.target_end_time > new Date().getTime()} />

            }
        </View>
    }

    function nextStepBtns() {
        return <View className="btn_bg">
            {
                (time.status == 'WAIT_FOR_START') &&
                <StartSleepBtn onClick={showPicker} />
            }
            {
                time.status == 'ONGOING1' && <EndFastBtn onClick={showPicker} lowLight={time.fast.target_end_time > new Date().getTime()} />
            }
            {
                time.status == 'ONGOING2' && <EndFastBtn onClick={showPicker} lowLight={time.fast.target_end_time > new Date().getTime()} />

            }
        </View>
    }


    function fastBtns() {
        return <View className="btn_bg">
            {
                time.status == 'ONGOING' ? <EndFastBtn onClick={showPicker} lowLight={textAlpha(time) != 1} /> : <StartFastBtn onClick={showPicker} />
            }
        </View>
    }

    function sleepBtns() {
        return <View className="btn_bg">
            {
                time.status == 'ONGOING' ? <EndSleepBtn onClick={showPicker} lowLight={textAlpha(time) != 1} /> : <StartSleepBtn onClick={showPicker} />
            }
        </View>
    }

    function durationChange(e) {
        var count = (e[0] + common.duration.min) * 60 + e[1] * common.duration.step
        isFast ? setFastDuration(count * 60000) : setSleepDuration(count * 60000);
        isFast ? setFastPickerValue(e) : setSleepPickerValue(e)
        var node = durationPickerContent()
        global.showClockModal2(false, node)
    }

    function login() {
        jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
    }

    function durationFormate() {
        var t = isFast ? fastDuration / 60000 : sleepDuration / 60000
        if (props.isNextStep) t = sleepDuration / 60000
        var hour = Math.floor(t / 60)
        var minute = Math.floor(t % 60)
        return `${hour > 0 ? hour + '小时' : ''}${minute > 0 ? minute + '分钟' : ''}`
    }

    function showDurationPicker(e) {
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }
        // var node = <Modal children={durationPickerContent()} dismiss={() => global.showClockModal2(false, null)} confirm={() => {
        //     var picker = durationPickerRef.current;
        //     durationChange((picker as any).getConfirmData());
        //     global.showClockModal2(false, null);
        // }} />
        var node = durationPickerContent()
        global.showClockModal2(true, node);
    }




    function durationPickerContent() {
        var color = getColor(time)
        var title = getDurationTitle(time, t)
        console.log('duration', fastPickerValue)
        return <View style={{ color: '#fff', backgroundColor: 'transparent' }}>
            <PickerViews ref={durationPickerRef}
                onChange={durationChange}
                items={durationDatas(common)}
                value={isFast ? fastPickerValue : sleepPickerValue}
                themeColor={color}
                title={title}
                showBtns={true} onCancel={() => { global.showClockModal2(false, durationPickerContent()); }} />
        </View>
    }

    function minus() {
        if (isFast) {
            var count = fastDuration - common.duration.step * 60 * 1000
            count = count < 3600000 ? 3600000 : count

            setFastDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setFastPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
        else {
            var count = sleepDuration - common.duration.step * 60 * 1000
            count = count < 3600000 ? 3600000 : count

            setSleepDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setSleepPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
    }

    function plus() {
        if (isFast) {
            var count = fastDuration + common.duration.step * 60 * 1000
            count = count > 23 * 3600000 ? 23 * 3600000 : count

            setFastDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setFastPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
        else {
            var count = sleepDuration + common.duration.step * 60 * 1000

            count = count > 23 * 3600000 ? 23 * 3600000 : count

            setSleepDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setSleepPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
    }

    function disableMinus() {
        if (isFast) {
            if (fastDuration <= 60 * 60 * 1000) {
                return true;
            }
        }
        else {
            if (sleepDuration <= 60 * 60 * 1000) {
                return true;
            }
        }
        return false;
    }

    function disablePlus() {
        if (isFast) {
            if (fastDuration >= 23 * 60 * 60 * 1000) {
                return true;
            }
        }
        else {
            if (sleepDuration >= 23 * 60 * 60 * 1000) {
                return true;
            }
        }
        return false;
    }

    var textColor = getColor(time)
    if (time.status != 'ONGOING1' && time.status != 'WAIT_FOR_START') {
        if (textAlpha(time) == 1) {
            textColor = '#FA5151';
        }
    }

    if (!user.isLogin) {
        return <View style={{ display: 'flex', flexDirection: 'column', width: '100%', alignItems: 'center' }}>
            <Text>16:00</Text>
            <Text style={{ color: global.fastColor ? global.fastColor : ColorType.fast }} onClick={login}>Start Fast</Text>
        </View>
    }

    if (props.isNextStep) {
        return <Box >
            <View style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0,
                opacity: time.status == 'WAIT_FOR_START' ? 0.4 : 1,
                pointerEvents: time.status == 'WAIT_FOR_START' ? 'none' : 'all'
            }}>
                {
                    (time.status == 'WAIT_FOR_START') && <Stepper child={
                        <Text className="stepper_text" style={{ color: global.sleepColor ? global.sleepColor : ColorType.sleep, opacity: textAlpha(time) }} onClick={showDurationPicker}>{durationFormate()}</Text>
                    } minus={minus} plus={plus}
                        themeColor={global.sleepColor ? global.sleepColor : ColorType.sleep} disableMinus={disableMinus()} disablePlus={disablePlus()} />
                }
                {
                    (time.status == 'ONGOING1' || time.status == 'ONGOING2') &&
                    <View className="console_time_bg">
                        <Text className={textNextStepAlpha(time) == 1 ?
                            'console_time_value  timeout_fast_linear_color' :
                            'console_time_value normal_fast_color'}
                            style={{
                                opacity: textNextStepAlpha(time) == 1 ? 1 : 0.8
                            }}>
                            {TimeFormatter.countdown(time.fast.target_end_time)}</Text>
                        <Text className="console_time_duration" style={{ color: global.fastColor ? global.fastColor : ColorType.fast, opacity: 0.4 }}>{
                            TimeFormatter.calculateTimeDifference(time.fast.target_start_time,
                                time.fast.target_end_time, true)}</Text>



                    </View>
                }

                <View>
                    {
                        nextStepBtns()
                    }
                </View>
            </View>
        </Box>
    }

    function getClassName(isFast) {
        if (isFast) {
            if (textAlpha(time) == 1) {
                return 'console_time_value  timeout_fast_linear_color'
            }
            else {
                return 'console_time_value normal_fast_color'
            }

        }
        else {
            if (textAlpha(time) == 1) {
                return 'console_time_value timeout_sleep_linear_color'
            }
            else {
                return 'console_time_value normal_sleep_color'
            }
        }
    }

    function ongoing() {
        if (time.status == 'ONGOING' || time.status == 'ONGOING2' || time.status == 'ONGOING3') {
            var isFastData = time.scenario == 'FAST' || time.status == 'ONGOING3'
            var duration = TimeFormatter.calculateTimeDifference(isFastData ? time.fast.target_start_time : time.sleep.target_start_time,
                isFast ? time.fast.target_end_time : time.sleep.target_end_time, true);
            return <View className="console_time_bg">

                <Text className={getClassName(isFastData)} style={{ opacity: textAlpha(time) == 1 ? 1 : 0.8 }}>{isFastData ?
                    TimeFormatter.countdown(time.fast.target_end_time) :
                    TimeFormatter.countdown(time.sleep.target_end_time)}</Text>
                <Text className="console_time_duration" style={{ color: isFastData ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep, opacity: 0.4 }}>{duration}</Text>
            </View>
        }
        return <View />
    }
    return (
        <Box >
            <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                {
                    isLoaded && ongoing()
                }
                {
                    (time.status == 'ONGOING1' || time.status == 'WAIT_FOR_START') && <Stepper child={
                        <Text className="stepper_text" style={{ color: textColor, opacity: textAlpha(time) }} onClick={showDurationPicker}>{durationFormate()}</Text>
                    } minus={minus} plus={plus}
                        themeColor={isFast ? global.fastColor ? global.fastColor : ColorType.fast : global.sleepColor ? global.sleepColor : ColorType.sleep} disableMinus={disableMinus()} disablePlus={disablePlus()} />
                }

                <View>
                    {
                        time.scenario === 'FAST_SLEEP' && mixedBtns()
                    }
                    {
                        time.scenario === 'FAST' && fastBtns()
                    }
                    {
                        time.scenario === 'SLEEP' && sleepBtns()
                    }
                </View>
            </View>
        </Box>
    )
}