import { View, Text, Image } from "@tarojs/components";
import './ChooseScenario.scss'
import { useRouter } from "@tarojs/taro";
import { kIsIOS, 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";
import { getLocalPush } from "@/features/trackTimeDuration/actions/TrackTimeActions";

let OneSignal
let NativeAppEventEmitter
let Jto
let uploadPermissions, checkNotification, PushNotification
if (process.env.TARO_ENV == 'rn') {
    OneSignal = require('react-native-onesignal').OneSignal
    NativeAppEventEmitter = require('react-native').NativeAppEventEmitter
    Jto = require('react-native').NativeModules.NativeBridge;
    uploadPermissions = require('@/utils/native_permission_check').uploadPermissions;
    checkNotification = require('@/utils/native_permission_check').checkNotification;
    PushNotification = require('react-native-push-notification')
}

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 [authStatus, setAuthStatus] = useState('')
    const [btnDisable, setBtnDisable] = useState(false)
    const { t } = useTranslation()
    const dispatch = useDispatch();

    useEffect(() => {
        if (navigation) {
            navigation.setOptions({
                headerTitle: '',
            });
        }
        if (process.env.TARO_ENV == 'rn') {
            rnNotification()
        }
    }, [])

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


    function rnNotification() {
        if (kIsIOS) {
            Jto.getNotificationAuthStatus()
            NativeAppEventEmitter.addListener('notificationResult', (data) => {
                setAuthStatus(data)
                global.notification = data
                uploadPermissions()
            })
            NativeAppEventEmitter.addListener('operateNotificationResult', (data) => {
                getLocalPush()
                global.notification = data
                navigation.popToTop()
                uploadPermissions()
            })
        }
        else {
            OneSignal.Notifications.canRequestPermission().then((status) => {
                if (status) {
                    OneSignal.Notifications.getPermissionAsync().then((res) => {
                        if (res) {
                            global.notification = 'authorized'
                            uploadPermissions()
                        }
                        else {
                            global.notification = 'denied'
                            uploadPermissions()
                        }
                    })
                }
                else {
                    global.notification = 'not_determined'
                    uploadPermissions()
                }
            })

        }
    }

    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 = ''
        if (hours > 0) {
            str = hours + (global.language == 'en' ? ' hours' : '小时')// + minutes + ' minutes'
        }
        if (minutes > 0) {
            if (global.language == 'en') {
                str += ` ${minutes}` + (global.language == 'en' ? ' minutes' : '分钟')
            }
            else {
                str += `${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 = ''
        if (hours > 0) {
            str = hours + (global.language == 'en' ? ' hours' : '小时')// + minutes + ' minutes'
        }
        if (minutes > 0) {
            if (global.language == 'en') {
                str += ` ${minutes}` + (global.language == 'en' ? ' minutes' : '分钟')
            }
            else {
                str += `${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() {
        setBtnDisable(true)
        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: parseInt(router.params.isSelf + '') == 1 ? null : {
                    input_value: target.sleep.schedule.sleep.latency.init_value,
                },
                cycle: parseInt(router.params.isSelf + '') == 1 ? null : {
                    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 => {
            setBtnDisable(false)
            if (global.checkData) {
                global.checkData()
            }

            if (global.indexPageRefresh) {
                global.indexPageRefresh()
            }
            global.chooseMixed()

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


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

    function popAlert() {


        if (process.env.TARO_ENV === 'weapp') {
            Taro.navigateBack({ delta: 6 }).then(res => {

            })
        }
        else {
            navigation.popToTop()
        }
        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() {
        debugger
        if (target.isMixed) {
            popMixScheduleAlert(fastTarget.start_time, sleepTarget.start_time)
        }
        else {
            popScheduleAlert({
                name: 'FAST'
            }, fastTarget.start_time)
        }
    }

    function popScheduleAlert(scenario, startTime) {
        if (process.env.TARO_ENV === 'rn') {
            PushNotification.checkPermissions((res) => {
                //允许授权
                if ((kIsIOS && res.authorizationStatus == 2) || (!kIsIOS && res.alert)) {
                    getLocalPush();
                    navigation.popToTop()
                    // showAlert({
                    //     title: t('feature.track_time_duration.reminders.schedule_title'),
                    //     content: scenario.name == 'FAST' ?
                    //         t('feature.track_time_duration.reminders.enable_schedule_fast_content', { time: startTime }) :
                    //         t('feature.track_time_duration.reminders.enable_schedule_sleep_content', { time: startTime }),
                    //     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: scenario.name == 'FAST' ?
                            t('feature.track_time_duration.reminders.schedule_fast_content', { time: startTime }) :
                            t('feature.track_time_duration.reminders.schedule_sleep_content', { time: startTime }),
                        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 popMixScheduleAlert(time1, time2) {
        console.log(time1, time2)
        if (process.env.TARO_ENV === 'rn') {
            // const JPush = require('jpush-react-native').default;
            const checkNotification = require('@/utils/native_permission_check').checkNotification;
            PushNotification.checkPermissions((res) => {
                //允许授权
                if ((kIsIOS && res.authorizationStatus == 2) || (!kIsIOS && res.alert)) {
                    getLocalPush();
                    navigation.popToTop()
                    // showAlert({
                    //     title: t('feature.track_time_duration.reminders.schedule_title'),
                    //     content: t('feature.track_time_duration.reminders.enable_schedule_mix_content', { time1: time1, time2: time2 }),
                    //     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_mix_content'),
                        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={{ overflow: 'hidden' }}>
                <View className="cell_full" style={{
                    // marginLeft: rpxToPx(46),
                    // marginRight: rpxToPx(46),
                    // paddingLeft: rpxToPx(40),
                    // paddingRight: rpxToPx(40),
                    margin: 0,
                    // backgroundColor:'red'
                }} onClick={() => { }}>
                    <Text className="cell_title">{t('feature.set_goal.fast')}</Text>
                    <Text className="cell_value" style={{ color: ColorType.fast }}>{fastDuration}</Text>
                </View>
                {
                    target.isMixed && <View className="cell_line" style={{ marginLeft: -rpxToPx(46), marginRight: -rpxToPx(46) }} />
                }
                {
                    target.isMixed && <View className="cell_full" style={{
                        marginLeft: 0,
                        marginRight: 0,
                        paddingLeft: 0,
                        paddingRight: 0
                    }} onClick={() => { }}>
                        <Text className="cell_title">{t('feature.set_goal.sleep')}</Text>
                        <Text className="cell_value" style={{ color: ColorType.sleep }}>{sleepDuration}</Text>
                    </View>
                }
            </View>


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

            <View className="cell_bg" style={{ overflow: 'hidden' }}>
                <View className="cell_top" style={{
                    marginLeft: 0,
                    marginRight: 0,
                    paddingLeft: 0,
                    paddingRight: 0
                }} onClick={() => {
                    setIsFast(true)
                    setIsStart(true)
                    setShowTimePicker(true)
                }}>
                    <Text className="cell_title">{t('feature.set_goal.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_line" style={{ marginLeft: -rpxToPx(46), marginRight: -rpxToPx(46) }} />
                }
                {
                    target.isMixed && <View className="cell_top" style={{
                        marginLeft: 0,
                        marginRight: 0,
                        paddingLeft: 0,
                        paddingRight: 0
                    }} onClick={() => {
                        setIsFast(false)
                        setIsStart(true)
                        setShowTimePicker(true)
                    }}>
                        <Text className="cell_title">{t('feature.set_goal.go_to_bed')}</Text>
                        <Text className="cell_value" style={{ color: ColorType.sleep }}>{isNextDay(false, true) ? t('feature.set_goal.next_day') : ' '}{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_line" style={{ marginLeft: -rpxToPx(46), marginRight: -rpxToPx(46) }} />
                }
                {
                    target.isMixed && <View className="cell_bottom" style={{
                        marginLeft: 0,
                        marginRight: 0,
                        paddingLeft: 0,
                        paddingRight: 0
                    }} onClick={() => {
                        setIsFast(false)
                        setIsStart(false)
                        setShowTimePicker(true)
                    }}>
                        <Text className="cell_title">{t('feature.set_goal.wake_up')}</Text>

                        <Text className="cell_value" style={{ color: ColorType.sleep }}>{isNextDay(false, false) ? t('feature.set_goal.next_day') : ' '}{sleepTarget.end_time}</Text>
                        <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
                    </View>
                }
                <View className="cell_line" style={{ marginLeft: -rpxToPx(46), marginRight: -rpxToPx(46) }} />

                <View className="cell_bottom" style={{
                    marginLeft: 0,
                    marginRight: 0,
                    paddingLeft: 0,
                    paddingRight: 0
                }} onClick={() => {
                    setIsFast(true)
                    setIsStart(false)
                    setShowTimePicker(true)
                }}>
                    <Text className="cell_title">{t('feature.set_goal.end_fasting')}</Text>

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

            {
                parseInt(router.params.isSelf + '') != 1 && <Text className="cell_footer">{t('feature.set_goal.footer')}</Text>
            }

        </View>

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

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