import { View, Text, Image } from '@tarojs/components'
import './IndexConsole.scss'
import { useTranslation } from 'react-i18next'
import { useSelector } from 'react-redux';
import { endFast, endSleep, startFast, startSleep } from "../actions/TrackTimeActions";
import { jumpPage } from '../hooks/Common';
import { useEffect, useRef, useState } from 'react';
import LimitPickers from '@/components/input/LimitPickers';
import { getColor, getTimePickerTitle } from '../hooks/Console';
import { rpxToPx, vibrate } from '@/utils/tools';
import { TimeFormatter } from '@/utils/time_format';

let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}
let operateType = ''
export default function IndexConsole(props: { record: any }) {
    const user = useSelector((state: any) => state.user);
    const { status } = props.record.current_record;
    const currentRecord = props.record.current_record;
    const { t } = useTranslation()
    const [fastDuration, setFastDuration] = useState<number>(0);
    const [sleepDuration, setSleepDuration] = useState<number>(0);
    const [expand, setExpand] = useState(false);

    // const [fastPickerValue, setFastPickerValue] = useState([0, 0])
    // const [sleepPickerValue, setSleepPickerValue] = useState([0, 0])

    const limitPickerRef = useRef(null)

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

    useEffect(() => {
        if (currentRecord.fast) {
            var fastCount = currentRecord.fast.target_end_time - currentRecord.fast.target_start_time
            setFastDuration(fastCount)
        }

        if (currentRecord.sleep) {
            var sleepCount = currentRecord.sleep.target_end_time - currentRecord.sleep.target_start_time
            setSleepDuration(sleepCount)
        }



    }, [props.record])


    function tapStartFast() {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return
        }

        operateType = 'startFast'

        showPicker()
    }

    function tapStartSleep() {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth')
            return
        }
        if (status != 'ONGOING1' && props.record.scenario.name == 'FAST_SLEEP') {
            vibrate()
            return;
        }
        operateType = 'startSleep'

        showPicker()
    }

    function tapEndSleep() {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth')
            return
        }
        if (status != 'ONGOING2' && status!='ONGOING') {
            vibrate()
            return;
        }
        operateType = 'endSleep'

        showPicker()
    }

    function tapEndFast() {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth')
            return
        }
        if (status == 'WAIT_FOR_START') {
            vibrate()
            return;
        }
        operateType = 'endFast'

        showPicker()
    }

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

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

        var title = getTimePickerTitle(currentRecord, t, operateType == 'endFast')
        var color = getColor(currentRecord, operateType == 'endFast')
        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 showPicker() {
        // global.scenario = 'FAST_SLEEP'
        if (global.testInfotimer) {
            return
        }
        global.set_time = new Date().getTime()
        updateNodeInfo()
        if (!global.isDebug) {
            return
        }
        // global.testInfotimer = setInterval(() => {
        // updateNodeInfo()

        // }, 1000)

    }

    function updateNodeInfo() {
        var node = layoutContent()
        global.showIndexModal(true, node, null);
    }

    function hidePicker() {
        var node = layoutContent()
        global.showIndexModal(false, node, null);
    }

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

        t = date.getTime();

        switch (operateType) {
            case 'startFast':
                startFast(t, fastDuration).then(res => {
                    global.indexPageRefresh()
                })
                break
            case 'startSleep':
                startSleep(t, sleepDuration).then(res => {
                    global.indexPageRefresh()
                })
                break
            case 'endSleep':
                endSleep(t).then(res => {
                    global.indexPageRefresh()
                })
                break
            case 'endFast':
                endFast(t).then(res => {
                    global.indexPageRefresh()
                })
                break
        }
    }


    if (props.record.scenario.name == 'FAST') {
        return <View style={{ marginTop: rpxToPx(40) }}>
            {
                status == 'WAIT_FOR_START' &&
                <View onClick={tapStartFast} className='console_btn'>
                    <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.start_fast')}</Text>
                </View>
            }
            {
                status == 'WAIT_FOR_START' && <View className='btn_line' />
            }
            <View onClick={tapEndFast} className={status == 'ONGOING' ? 'console_btn' : 'console_btn btn_disable'}>
                <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.end_fast')}</Text>
            </View>
        </View>
    }
    else if (props.record.scenario.name == 'SLEEP') {
        return <View style={{ marginTop: rpxToPx(40) }}>
            {
                status == 'WAIT_FOR_START' &&
                <View onClick={tapStartSleep} className='console_btn btn_sleep'>
                    <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.start_sleep')}</Text>
                </View>
            }
            {
                status == 'WAIT_FOR_START' && <View className='btn_line' />
            }
            <View onClick={tapEndSleep} className={status == 'ONGOING' ? 'console_btn btn_sleep' : 'console_btn btn_sleep btn_disable'}>
                <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.end_sleep')}</Text>
            </View>
        </View>
    }

    return <View style={{ marginTop: rpxToPx(40) }}>
        {
            status == 'WAIT_FOR_START' ?
                <View onClick={tapStartFast} className='console_btn'>
                    <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.start_fast')}</Text>
                </View> :
                <View onClick={() => { vibrate() }} className='stage_btn'>
                    <Text style={{ flex: 1 }}>睡前断食</Text>
                    {
                        status == 'ONGOING1' ?
                            <Text>{TimeFormatter.countdown(currentRecord.fast.real_start_time)}</Text> :
                            <Text>{TimeFormatter.countdown(currentRecord.fast.real_start_time, currentRecord.sleep.real_start_time)}</Text>
                    }

                </View>
        }
        <View className='btn_line' />
        {
            (status == 'WAIT_FOR_START' || status == 'ONGOING1') &&
            <View onClick={tapStartSleep} className={status == 'ONGOING1' ? 'console_btn btn_sleep' : 'console_btn btn_sleep btn_disable'}>
                {
                    status != 'ONGOING1' && <Image className='lock' src={require('@assets/images/lock.png')} />
                }
                <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.start_sleep')}</Text>
            </View>
        }
        {
            (status != 'WAIT_FOR_START' && status != 'ONGOING1') &&
            <View onClick={() => { vibrate() }} className='stage_btn'>
                <Text style={{ flex: 1 }}>睡眠期间断食</Text>
                {
                    status == 'ONGOING2' ? <Text>{TimeFormatter.countdown(currentRecord.sleep.real_start_time)}</Text> :
                        <Text>{TimeFormatter.countdown(currentRecord.sleep.real_start_time, currentRecord.sleep.real_end_time)}</Text>
                }


            </View>
        }
        {(expand || (status != 'WAIT_FOR_START' && status != 'ONGOING1')) && <View className='btn_line' />}
        {
            (expand || (status != 'WAIT_FOR_START' && status != 'ONGOING1')) && (status == 'WAIT_FOR_START' || status == 'ONGOING1' || status == 'ONGOING2') &&
            <View onClick={tapEndSleep} className={status == 'ONGOING2' ? 'console_btn btn_sleep' : 'console_btn btn_sleep btn_disable'}>
                {
                    status != 'ONGOING2' && <Image className='lock' src={require('@assets/images/lock.png')} />
                }
                <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.end_sleep')}</Text>
            </View>
        }
        {
            status == 'ONGOING3' &&
            <View onClick={() => { vibrate() }} className='stage_btn'>
                <Text style={{ flex: 1 }}>起床后断食</Text>
                <Text>{TimeFormatter.countdown(currentRecord.sleep.real_end_time)}</Text>
            </View>
        }
        {(expand || (status != 'WAIT_FOR_START')) && <View className='btn_line' />}
        {
            (expand || status != 'WAIT_FOR_START') && (status == 'WAIT_FOR_START' || status == 'ONGOING1' || status == 'ONGOING2' || status == 'ONGOING3') &&
            <View onClick={tapEndFast} className={status == 'ONGOING3' ? 'console_btn' : 'console_btn btn_disable'}>
                {
                    status == 'WAIT_FOR_START' && <Image className='lock' src={require('@assets/images/lock.png')} />
                }
                <Text style={{ fontWeight: 'bold' }}>{t('feature.track_time_duration.common.end_fast')}</Text>
            </View>
        }
        {
            (status == 'WAIT_FOR_START' || status == 'ONGOING1') &&
            <View>
                {
                    expand ? <Text className='expand' onClick={() => { setExpand(false) }}>收起</Text> : <Text className='expand' onClick={() => { setExpand(true) }}>展开</Text>
                }
            </View>
        }

    </View>
}