
import { View, Text, PickerView } 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, 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";

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 limitPickerRef = useRef(null)
    const durationPickerRef = useRef(null)
    const dispatch = useDispatch();

    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))
        }

        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)
            }
        }
    }


    function showPicker() {
        if (global.testInfotimer) {
            return
        }
        global.set_time = new Date().getTime()
        updateNodeInfo()
        global.testInfotimer = setInterval(() => {
            updateNodeInfo()

        }, 1000)

    }

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

    function hidePicker() {
        global.showClockModal(false, 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 />
        }
        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 <View style={{ color: '#fff', paddingTop: 30, paddingLeft: 30, display: 'flex', flexDirection: 'column' }}>
            <Text>check scenario:{isFast ? 'fast' : 'sleep'}</Text>
            <Text>check type:{isStart ? 'start' : 'end'}</Text>
            <Text style={{ marginTop: 30 }}>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: 30 }}>now:{TimeFormatter.formatTimestamp(new Date().getTime())}</Text>
            <Text>elapsed:{TimeFormatter.calculateTimeDifference(global.picker_time, new Date().getTime())}</Text>

            <Text style={{ marginTop: 30 }}>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>
    }


    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()) {
                limit = limit + 60 * 1000
            }
        }

        var title = getTitle(time)
        var color = getColor(time)
        if (props.isNextStep) {
            title = '结束断食'
            color = '#AAFF00'
        }


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

    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;
        }

        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'
                        dispatch(changeConsoleStatus({status:ConsoleType.going}));
                    }
                });
            }
            else {
                endFast(t)
            }
        }
        else {
            if (time.status == 'WAIT_FOR_START' || time.status == 'ONGOING1') {
                startSleep(t, sleepDuration);
            }
            else {
                endSleep(t)
            }
        }
    }

    function targetView() {
        if (props.isNextStep && (time.status == 'ONGOING1' || time.status == 'ONGOING2')) {
            var opacity = textNextStepAlpha(time)
            if (opacity == 1) {
                return <View className="target_view" style={{ backgroundColor: '#FA51511A' }}>
                    <Text className="target_text" style={{ color: '#FA5151' }}>超出目标结束</Text>
                </View>
            }
            return <View className="target_view" style={{ backgroundColor: '#AAFF001A', opacity: opacity }}>
                <Text className="target_text" style={{ color: '#AAFF00' }}>距离目标结束</Text>
            </View>
        }

        if (time.status == 'ONGOING' || time.status == 'ONGOING2' || time.status == 'ONGOING3') {
            var opacity = textAlpha(time)
            if (opacity == 1) {
                return <View className="target_view" style={{ backgroundColor: '#FA51511A' }}>
                    <Text className="target_text" style={{ color: '#FA5151' }}>超出目标结束</Text>
                </View>
            }
            return <View className="target_view" style={{ backgroundColor: isFast ? '#AAFF001A' : '#00FFFF1A', opacity: opacity }}>
                <Text className="target_text" style={{ color: isFast ? '#AAFF00' : '#00FFFF' }}>距离目标结束</Text>
            </View>
        }
        return <View />
    }

    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)
        global.showClockModal2(false, null)
    }

    function login() {
        Taro.navigateTo({
            url: '/pages/account/ChooseAuth'
        })
    }

    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() {
        var node = <Modal children={durationPickerContent()} dismiss={() => global.showClockModal2(false, null)} confirm={() => {
            var picker = durationPickerRef.current;
            durationChange((picker as any).getConfirmData());
            global.showClockModal2(false, null);
        }} />
        global.showClockModal2(true, node);
    }




    function durationPickerContent() {
        var color = getColor(time)
        var title = getTitle(time)
        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, null); }} />
        </View>
    }

    function minus() {
        if (isFast) {
            var count = fastDuration - 5 * 60 * 1000
            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 - 5 * 60 * 1000

            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 + 5 * 60 * 1000
            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 + 5 * 60 * 1000

            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: '#AAFF00' }} 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: '#00FFFF', opacity: textAlpha(time) }} onClick={showDurationPicker}>{durationFormate()}</Text>
                    } minus={minus} plus={plus} disableMinus={disableMinus()} disablePlus={disablePlus()} />
                }
                {
                    time.status == 'ONGOING1' && <View>
                        <Text className="counter_text" style={{ color: textNextStepAlpha(time) == 1 ? '#FA5151' : '#AAFF00', opacity: textNextStepAlpha(time) }}>{TimeFormatter.countdown(time.fast.target_end_time)}</Text>
                    </View>
                }

                {
                    time.status == 'ONGOING2' && <View>
                        <Text className="counter_text" style={{ color: textNextStepAlpha(time) == 1 ? '#FA5151' : '#AAFF00', opacity: textNextStepAlpha(time) }}>{TimeFormatter.countdown(time.fast.target_end_time)}</Text>
                    </View>
                }
                {
                    targetView()
                }

                <View>
                    {
                        nextStepBtns()
                    }
                </View>
            </View>
        </Box>
    }
    return (
        <Box >
            <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                {
                    time.status == 'ONGOING' && <View>
                        <Text className="counter_text" style={{ color: textColor, opacity: textAlpha(time) }}>{time.scenario == 'FAST' ?
                            TimeFormatter.countdown(time.fast.target_end_time) :
                            TimeFormatter.countdown(time.sleep.target_end_time)}</Text>
                    </View>
                }
                {
                    (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} disableMinus={disableMinus()} disablePlus={disablePlus()} />
                }
                {
                    time.status == 'ONGOING2' && <View>
                        <Text className="counter_text" style={{ color: textColor, opacity: textAlpha(time) }}>{TimeFormatter.countdown(time.sleep.target_end_time)}</Text>
                    </View>
                }

                {
                    time.status == 'ONGOING3' && <View>
                        <Text className="counter_text" style={{ color: textColor, opacity: textAlpha(time) }}>{TimeFormatter.countdown(time.fast.target_end_time)}</Text>
                    </View>
                }
                {
                    targetView()
                }

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