import { View, Text, Image } from "@tarojs/components";
import './ChooseScenario.scss'
import { useRouter } from "@tarojs/taro";
import { rpxToPx } from "@/utils/tools";
import { ColorType } from "@/context/themes/color";
import Footer from "@/components/layout/Footer";
import { ChooseScenarioBtn, SetScheduleBtn } from "@/features/common/SpecBtns";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import Modal from "@/components/layout/Modal.weapp";
import TimePicker from "@/features/common/TimePicker";
import { useTranslation } from "react-i18next";
import { updateFast, updateSleep } from "@/store/set_target";
import { setPlan } from "@/services/trackTimeDuration";
import showAlert from "@/components/basic/Alert";
import Taro from "@tarojs/taro";

export default function SetGoal() {

    let router
    var navigation: any = null
    if (process.env.TARO_ENV === 'rn') {
        var useNavigation = require("@react-navigation/native").useNavigation
        navigation = useNavigation()
        const useRoute = require("@react-navigation/native").useRoute
        router = useRoute()
    }
    else {
        router = useRouter()
    }
    const isSelf = router.params.isSelf
    const target = useSelector((state: any) => state.target);
    const [fastDuration, setFastDuration] = useState<any>(0)
    const [sleepDuration, setSleepDuration] = useState<any>(0)
    const [fastTarget, setFastTarget] = useState(target.fast.schedule.fast)
    const [sleepTarget, setSleepTarget] = useState(target.sleep.schedule.sleep)
    const [showTimePicker, setShowTimePicker] = useState(false)
    const [isFast, setIsFast] = useState(true)
    const [isStart, setIsStart] = useState(true)
    const { t } = useTranslation()
    const dispatch = useDispatch();

    useEffect(() => {
        getFastDuration()
        getSleepDuration()
    }, [target.fast, target.sleep])

    function getFastDuration() {
        var obj = target.fast.schedule.fast
        var duration = obj.end_time.split(':')[0] * 60 + obj.end_time.split(':')[1] * 1 - (obj.start_time.split(':')[0] * 60 + obj.start_time.split(':')[1] * 1)
        if (duration <= 0) {
            duration += 24 * 60
        }
        var hours = Math.floor(duration / 60)
        var minutes = duration % 60
        var str = hours + ' hours ' + minutes + ' minutes'
        setFastDuration(str)
    }

    function getFastDurationMinutes(){
        var obj = target.fast.schedule.fast
        var duration = obj.end_time.split(':')[0] * 60 + obj.end_time.split(':')[1] * 1 - (obj.start_time.split(':')[0] * 60 + obj.start_time.split(':')[1] * 1)
        if (duration <= 0) {
            duration += 24 * 60
        }
        return duration
    }

    function getSleepDuration() {
        var obj = target.sleep.schedule.sleep
        var duration = obj.end_time.split(':')[0] * 60 + obj.end_time.split(':')[1] * 1 - (obj.start_time.split(':')[0] * 60 + obj.start_time.split(':')[1] * 1)
        if (duration <= 0) {
            duration += 24 * 60
        }
        var hours = Math.floor(duration / 60)
        var minutes = duration % 60
        var str = hours + ' hours ' + minutes + ' minutes'
        setSleepDuration(str)
    }

    function getSleepDurationMinutes(){
        var obj = target.sleep.schedule.sleep
        var duration = obj.end_time.split(':')[0] * 60 + obj.end_time.split(':')[1] * 1 - (obj.start_time.split(':')[0] * 60 + obj.start_time.split(':')[1] * 1)
        if (duration <= 0) {
            duration += 24 * 60
        }
        return duration
    }

    function hidePicker() {
        setShowTimePicker(false)
    }

    function modalContent() {
        return <Modal
            testInfo={null}
            dismiss={() => {
                hidePicker()
                // setShowTimeoutPicker(false)
            }}
            confirm={() => { }}>
            {
                timePickerContent()
            }
        </Modal>
    }

    function pickerTitle() {
        if (isFast) {
            if (isStart) {
                return t('feature.track_time_duration.dial.picker_fast_schedule_start_time');
            }
            return t('feature.track_time_duration.dial.picker_fast_schedule_end_time');
        }
        else {
            if (isStart) {
                return t('feature.track_time_duration.dial.picker_sleep_schedule_start_time');
            }
            return t('feature.track_time_duration.dial.picker_sleep_schedule_end_time');
        }
    }

    function pickerConfirm(e) {
        hidePicker()
        if (isFast) {
            var fast = JSON.parse(JSON.stringify(target.fast))

            if (isStart) {
                fast.schedule.fast.start_time = e
            }
            else {
                fast.schedule.fast.end_time = e
            }
            dispatch(updateFast({ fast: fast }))
            setFastTarget(fast.schedule.fast)
        }
        else {
            var sleep = JSON.parse(JSON.stringify(target.sleep))

            if (isStart) {
                sleep.schedule.sleep.start_time = e
            }
            else {
                sleep.schedule.sleep.end_time = e
            }
            dispatch(updateSleep({ sleep: sleep }))
            setSleepTarget(sleep.schedule.sleep)
        }

        getFastDuration()
        getSleepDuration()
    }

    function timePickerContent() {
        var time = ''
        if (isFast) {
            if (isStart) {
                time = fastTarget.start_time
            }
            else {
                time = fastTarget.end_time
            }
        }
        else {
            if (isStart) {
                time = sleepTarget.start_time
            }
            else {
                time = sleepTarget.end_time
            }
        }
        return <TimePicker time={time}
            color={isFast ? ColorType.fast : ColorType.sleep}
            title={pickerTitle()}
            confirm={pickerConfirm}
            cancel={hidePicker} />
    }

    function confirm() {
        var params: any = {
            method: parseInt(router.params.isSelf + '') == 1 ? 'USER_SET' : 'SUGGEST',
            schedule: {
                fast: {
                    start_time: fastTarget.start_time,
                    end_time: fastTarget.end_time,
                    duration: {
                        input_value: getFastDurationMinutes()//target.fast.schedule.fast.duration.init_value,
                    }
                },
            }
        }
        if (target.isMixed) {
            params.scenario = 'FAST_SLEEP'
            params.schedule.sleep = {
                start_time: sleepTarget.start_time,
                end_time: sleepTarget.end_time,
                duration:{
                    input_value:getSleepDurationMinutes()
                },
                latency: {
                    input_value: target.sleep.schedule.sleep.latency.init_value,
                },
                cycle: {
                    num: {
                        input_value: target.sleep.schedule.sleep.cycle.num.init_value,
                    }
                }
            }
        }
        else {
            params.scenario = 'FAST'
        }

        if (router.params.upgrade) {
            params.trigger_event = router.params.trigger_event
        }
        else {
            params.trigger_event = router.params.trigger_event ? router.params.trigger_event : 'SET'
        }

        setPlan(params).then(res => {
            if (global.checkData) {
                global.checkData()
            }

            if (global.indexPageRefresh) {
                global.indexPageRefresh()
            }
            // popMixScheduleAlert(scenario.schedule.fast.start_time, startTime)

            if (process.env.TARO_ENV === 'rn') {
                popRNAlert()
            }
            else {
                popAlert()
            }


        }).catch(e => {
        })
    }

    function popAlert() {
        global.chooseMixed()
        Taro.navigateBack({ delta: 6 }).then(res => {

        })
        if (target.isMixed) {
            setTimeout(() => {
                global.popMixScheduleAlert(fastTarget.start_time, sleepTarget.start_time)
            }, 800)
        }
        else {
            setTimeout(() => {
                global.popScheduleAlert({
                    name: 'FAST'
                }, fastTarget.start_time)
            }, 800)
        }
    }

    function popRNAlert() {
        // if (target.isMixed) {

        // }
        // else {
        //     const JPush = require('jpush-react-native').default;
        //     JPush.isNotificationEnabled((res) => {
        //         if (res) {
        //             showAlert({
        //                 title: t('feature.track_time_duration.reminders.schedule_title'),
        //                 content:
        //                     t('feature.track_time_duration.reminders.enable_schedule_fast_content', { time: fastTarget.start_time }),
        //                 showCancel: false,
        //                 confirmText: t('feature.track_time_duration.reminders.ok'),
        //                 cancel: () => {
        //                     navigation.popToTop()
        //                 },
        //                 confirm: () => {
        //                     navigation.popToTop()
        //                 },
        //             })
        //         }
        //         else {
        //             showAlert({
        //                 title: t('feature.track_time_duration.reminders.schedule_title'),
        //                 content:
        //                     t('feature.track_time_duration.reminders.schedule_fast_content', { time: fastTarget.start_time }),
        //                 cancelText: t('feature.track_time_duration.reminders.later'),
        //                 confirmText: t('feature.track_time_duration.reminders.open'),
        //                 showCancel: true,
        //                 cancel: () => {
        //                     navigation.popToTop()
        //                 },
        //                 confirm: () => {
        //                     // if (authStatus != 'not_determined') {
        //                     //     navigation.popToTop()
        //                     // }
        //                     // checkNotification()
        //                     // Linking.openURL('app-settings:notifications')
        //                 }
        //             })
        //         }
        //     })
        // }
    }

    function isNextDay(isFast: boolean, isStart: boolean) {
        var time = fastTarget.start_time.split(':')[0] * 60 + fastTarget.start_time.split(':')[1] * 1
        if (isFast) {
            var time2 = fastTarget.end_time.split(':')[0] * 60 + fastTarget.end_time.split(':')[1] * 1
            return time2 <= time
        }
        else {
            if (isStart) {
                time2 = sleepTarget.start_time.split(':')[0] * 60 + sleepTarget.start_time.split(':')[1] * 1
                return time2 <= time
            }
            else {
                time2 = sleepTarget.end_time.split(':')[0] * 60 + sleepTarget.end_time.split(':')[1] * 1
                return time2 <= time
            }
        }
    }

    return <View style={{ display: 'flex', flexDirection: 'column',flex:1 }}>
        <Text className="target_title">{isSelf ? t('feature.set_goal.set_action_plan') : t('feature.set_goal.almost_done')}</Text>
        {
            !isSelf && <Text className="target_desc">{t('feature.set_goal.header')}</Text>
        }

        <View style={{ color: '#fff' }}>
            <View className="cell_bg" style={{ padding: 0 }}>
                <View className="cell_full" style={{
                    marginLeft: rpxToPx(46),
                    marginRight: rpxToPx(46),
                    paddingLeft: rpxToPx(40),
                    paddingRight: rpxToPx(40),
                    margin: 0
                }} onClick={() => { }}>
                    <Text className="cell_title">Fasting</Text>
                    <Text className="cell_value" style={{ color: ColorType.fast }}>{fastDuration}</Text>
                </View>
                {
                    target.isMixed && <View className="cell_full" style={{
                        marginLeft: rpxToPx(46),
                        marginRight: rpxToPx(46),
                        paddingLeft: rpxToPx(40),
                        paddingRight: rpxToPx(40),
                        margin: 0
                    }} onClick={() => { }}>
                        <Text className="cell_title">Sleep</Text>
                        <Text className="cell_value" style={{ color: ColorType.sleep }}>{sleepDuration}</Text>
                    </View>
                }
            </View>


            <View style={{ height: rpxToPx(20) }} />

            <View className="cell_bg" style={{ padding: 0 }}>
                <View className="cell_top" style={{ margin: 0 }} onClick={() => {
                    setIsFast(true)
                    setIsStart(true)
                    setShowTimePicker(true)
                }}>
                    <Text className="cell_title">Start fasting</Text>
                    <Text className="cell_value" style={{ color: ColorType.fast }}>{fastTarget.start_time}</Text>
                    <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                    <View className="cell_line" style={{ height: 1 }} />
                </View>
                {
                    target.isMixed && <View className="cell_top" style={{ margin: 0 }} onClick={() => {
                        setIsFast(false)
                        setIsStart(true)
                        setShowTimePicker(true)
                    }}>
                        <Text className="cell_title">Go to bed</Text>
                        <Text className="cell_value" style={{ color: ColorType.sleep }}>{isNextDay(false, true) ? '次日 ' : ' '}{sleepTarget.start_time}</Text>
                        <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                        <View className="cell_line" style={{ height: 1 }} />
                    </View>
                }
                {
                    target.isMixed && <View className="cell_bottom" style={{ margin: 0 }} onClick={() => {
                        setIsFast(false)
                        setIsStart(false)
                        setShowTimePicker(true)
                    }}>
                        <Text className="cell_title">Wake up</Text>

                        <Text className="cell_value" style={{ color: ColorType.sleep }}>{isNextDay(false, false) ? '次日 ' : ' '}{sleepTarget.end_time}</Text>
                        <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                    </View>
                }
                <View className="cell_bottom" style={{ margin: 0 }} onClick={() => {
                    setIsFast(true)
                    setIsStart(false)
                    setShowTimePicker(true)
                }}>
                    <Text className="cell_title">End fasting</Text>

                    <Text className="cell_value" style={{ color: ColorType.fast }}>{isNextDay(true, false) ? '次日 ' : ' '}{fastTarget.end_time}</Text>
                    <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                </View>
            </View>

            <Text className="cell_footer">{t('feature.set_goal.footer')}</Text>
        </View>

        <View style={{ flex: 1 }} />

        <Footer>
            <ChooseScenarioBtn
                onClick={confirm}
                title={'Done'}
                background={ColorType.fast}
            />
        </Footer>
        {
            showTimePicker && modalContent()
        }
        {
            process.env.TARO_ENV == 'rn' && <View style={{ marginBottom: 40 }} />
        }
    </View>
}