import { View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { forwardRef, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import trackTimeService, { machine } from "@/store/trackTimeMachine"
import { recordCheck } from "@/services/trackTimeDuration";
import LimitPickers from "@/components/input/LimitPickers";
import { endFast } from "../actions/TrackTimeActions";
import Modal from "@/components/layout/Modal";
import { setStep } from "@/store/scenario";
import { TimeFormatter } from "@/utils/time_format";
import { ColorType } from "@/context/themes/color";

const Component = forwardRef((props, ref) => {
    const isFastFirst = true;
    const { t } = useTranslation()
    const scenario = useSelector((state: any) => state.scenario);
    const user = useSelector((state: any) => state.user);
    const [isOpen, setIsOpen] = useState(false);
    const [showModal, setShowModal] = useState(false);
    const limitPickerRef = useRef<any>(null);
    const dispatch = useDispatch();

    useEffect(() => {
        var value = trackTimeService.getSnapshot().value
    }, [machine.context.currentStatus])

    useEffect(() => {
        trackTimeService.onTransition(state => {
            var value = trackTimeService.getSnapshot().value
        });
    }, []);

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

    function waitActionSheet() {
        Taro.showActionSheet({
            itemList: [t('feature.track_time_duration.action_sheet.change_schedule'), t('feature.track_time_duration.action_sheet.switch_scenario')]
        })
            .then(res => {
                switch (res.tapIndex) {
                    case 0:
                        if (scenario.name == 'FAST_SLEEP') {
                            dispatch(setStep(isFastFirst ? 'fast' : 'sleep'))
                        }
                        else if (scenario.name == 'SLEEP') {
                            dispatch(setStep('sleep'))
                        }
                        else {
                            dispatch(setStep('fast'))
                        }
                        Taro.navigateTo({
                            url: '/pages/clock/SetSchedule'
                        })
                        break;
                    case 1:
                        Taro.navigateTo({
                            url: '/pages/clock/ChooseScenario'
                        })
                        break;
                }
            })
            .catch(err => {
                console.log(err.errMsg)
            })
    }

    function endFastActionSheet() {
        Taro.showActionSheet({
            itemList: [t('feature.track_time_duration.action_sheet.end_fast')]
        })
            .then(res => {
                console.log(res.tapIndex)
                switch (res.tapIndex) {
                    case 0:
                        {
                            setShowModal(true)
                            setIsOpen(true)
                            global.set_time = new Date().getTime()
                        }
                        break;
                }
            })
            .catch(err => {
                console.log(err.errMsg)
            })
    }

    function checkActionSheetData() {
        console.log('checkActionSheetData')
        if (!user.isLogin) {
            return login()
        }
        var state = trackTimeService.getSnapshot().value
        if ((state as any).FAST_SLEEP === 'WAIT_FOR_START' ||
            (state as any).FAST === 'WAIT_FOR_START' ||
            (state as any).SLEEP === 'WAIT_FOR_START') {
            waitActionSheet()
        }
        else if ((state as any).FAST_SLEEP === 'ONGOING1' ||
            (state as any).FAST_SLEEP === 'ONGOING2') {
            endFastActionSheet()
        }
        else if ((state as any).FAST_SLEEP === 'ONGOING3') {
            // Taro.showToast({
            //     title: '暂无更多操作',
            //     icon: 'none',
            //     duration: 2000
            // })
        }
    }

    global.checkActionSheetData = checkActionSheetData

    function layoutContent() {
        var limit = global.set_time - 7 * 3600 * 1000 * 24;
        var current_record = machine.context.checkData ? (machine.context.checkData as any).current_record : null;
        global.limit = limit
        if (current_record && current_record.last_real_check_time) {
            limit = current_record.last_real_check_time
            global.limit = limit
            
            //当set_time秒数<=latest_record_time秒数时,最小限制时间戳需+1分钟
            if (new Date(global.set_time).getSeconds() <= new Date(current_record.last_real_check_time).getSeconds()) {
                limit = limit + 60 * 1000
            }
        }

        
        return <LimitPickers ref={limitPickerRef}
        title = '结束断食'
        themeColor={global.fastColor?global.fastColor:ColorType.fast}
        limit={limit} onCancel={() => { setIsOpen(false); setShowModal(false) }} 
        onChange={(e) => {
            endFast(e)
            setIsOpen(false)
        }} />

    }

    function testLayout() {
        var current_record = machine.context.checkData ? (machine.context.checkData as any).current_record : null;
        if (current_record == null) {
            return <View />
        }
        return <View style={{ color: '#fff', paddingTop: 30, paddingLeft: 30, display: 'flex', flexDirection: 'column' }}>
            <Text>check scenario:fast</Text>
            <Text>check type: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:{TimeFormatter.formatTimestamp(current_record.fast.real_start_time)}</Text>
            <Text>real duration:{TimeFormatter.calculateTimeDifference(current_record.fast.real_start_time, new Date().getTime())}</Text>
        </View>
    }

    return (
        <View ref={ref} style={{ width: '100%', marginTop: 20, marginBottom: 20, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Text onClick={checkActionSheetData}>More Component</Text>
            {
                showModal && isOpen && <Modal children={layoutContent()} dismiss={() => setIsOpen(false)}
                    testInfo={testLayout()}
                    confirm={() => {
                        var picker = limitPickerRef.current;
                        endFast((picker as any).getConfirmData());
                        setIsOpen(false);
                    }} />
            }
            {/* {
                showModal && <AtFloatLayout
                    isOpened={isOpen}
                    onClose={() => {
                        setIsOpen(false)
                        setShowModal(false)
                    }}
                    title="">
                    {
                        layoutContent()
                    }


                </AtFloatLayout>
            } */}

        </View>
    )
}
)

export default Component;
