import { WindowType } from "@/utils/types";
import { View, Text, Image } from "@tarojs/components";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import './MainConsole.scss'
import { jumpPage } from "../trackTimeDuration/hooks/Common";
import Modal from "@/components/layout/Modal.weapp";
import { MainColorType } from "@/context/themes/color";
import ConsolePicker from "../trackTimeDuration/components/ConsolePicker";
import { clockTimes, updateSchedule, updateTarget } from "@/services/health";
import TimePicker from "../common/TimePicker";
import showActionSheet from "@/components/basic/ActionSheet";
import { rpxToPx } from "@/utils/tools";
import { setMode } from "@/store/health";
import { getCountownTime, getDuration, getScenario, getWindowStatus } from "./hooks/health_hooks";

let useNavigation;
let min = 0
let max = 0
let defaultTimestamp = 0

if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function MainConsole(props: { type: WindowType }) {
    const health = useSelector((state: any) => state.health);
    const user = useSelector((state: any) => state.user);
    const [showPicker, setShowPicker] = useState(false)
    const [showTimePicker, setShowTimePicker] = useState(false)
    const [operateType, setOperateType] = useState('')
    const [btnDisable, setBtnDisable] = useState(false)
    const [selItem, setSelItem] = useState<any>(null)
    const limitPickerRef = useRef(null)
    const dispatch = useDispatch()

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


    useEffect(() => {

    }, [props.type])

    function edit(item) {
        if (item.scenario != 'FAST' && item.scenario != 'SLEEP') {
            return
        }

        if (item.action == 'NA' || item.action == 'POST_MOMENT' || 'SLEEP_WAKE_UP' == item.action) {
            return;
        }
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return
        }
        console.log(item)
        setSelItem(item)
        setShowPicker(true)
    }


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

        setSelItem(item)

        switch (item.action) {
            case 'START':
                {
                    defaultTimestamp = new Date().getTime()
                    min = defaultTimestamp - 1 * 24 * 3600 * 1000
                    max = defaultTimestamp

                    setOperateType('startFast')
                    setShowTimePicker(true)
                }
                return;
            case 'END':
                {
                    defaultTimestamp = new Date().getTime()
                    // defaultTimestamp = e ? new Date().getTime() : logEventTimestamp
                    min = defaultTimestamp - 1 * 24 * 3600 * 1000
                    max = defaultTimestamp
                    setOperateType('endFast')
                    setShowTimePicker(true)
                }
                return;

        }
        jumpPage('/pages/clock/AddMoment?moment=' + JSON.stringify(item))
    }

    function operateTitle(item) {
        switch (item.action) {
            case 'START':
            case 'END':
                return '打卡'
        }
        return '记录'
    }

    function itemTitle(item: any) {
        if (health.mode == 'DAY' || health.mode == 'NIGHT') {
            return item.title
        }
        return dayjs(item.target.timestamp).format('HH:mm')
    }

    function itemValue(item: any) {
        let themeColor: any = getThemeColor()
        const scenario = getScenario(health.windows,health.mode)
        if (item.action == 'END' && !scenario.real) {
            themeColor = '#B2B2B2'
        }
        if (health.mode == 'DAY' || health.mode == 'NIGHT') {
            return <Text className="timeline_time">{dayjs(item.target.timestamp).format('HH:mm')}</Text>
        }
        if (item.action && item.action != 'NA')
            return <View className="timeline_operate" style={{ color: themeColor, backgroundColor: themeColor + '1A' }} onClick={() => record(item)}>{operateTitle(item)}</View>
        return <View />
    }

    function timelineItem(item: any, index: number, count: number) {
        return <View key={index} className="timeline_item" >
            <View className="timeline_left">
                {
                    health.mode != 'DAY' && health.mode != 'NIGHT' && <Text className="timeline_title">{item.title}</Text>
                }
                <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                    <Text className="timeline_time" onClick={() => edit(item)}>{itemTitle(item)}</Text>
                </View>

            </View>
            {
                itemValue(item)
            }
            {/* {
                item.action && item.action != 'NA' && 
            } */}
            <View className="border_footer_line" style={{ left: count - 1 == index ? -rpxToPx(64) : 0 }} />
        </View>
    }

    function timeContent() {
        return <Modal
            testInfo={null}
            dismiss={() => {
                setShowPicker(false)
            }}
            confirm={() => { }}>
            {
                pickerContent()
            }
        </Modal>
    }

    function pickerContent() {
        const timestamp = selItem.target.timestamp
        const strTime = dayjs(timestamp).format('HH:mm')

        var title, color;
        switch (selItem.scenario) {
            case 'FAST':
                title = operateType == 'endFast' ? '结束断食' : '开始断食'
                color = MainColorType.fast
                break;
            case 'SLEEP':
                title = operateType == 'endFast' ? '结束睡眠' : '开始睡眠'
                color = MainColorType.sleep
        }

        return <TimePicker time={strTime}
            color={color}
            title={title}
            confirm={(e) => {
                confirmPickerTime(e)
            }}
            cancel={() => {
                setShowPicker(false)
            }} />
    }

    function confirmPickerTime(strTime) {
        if (selItem.event == 'FAST_END') {
            const obj = health.windows.fast_eat.fast.timeline[0]
            if (obj.action == 'POST_MOMENT' || obj.action == 'NA') {
                const format = dayjs(obj.target.timestamp).format(`YYYY-MM-DDT${strTime}:ss`)
                var t = new Date(format).getTime()
                if (t <= obj.target.timestamp) {
                    t += 24 * 3600 * 1000
                }
                updateTarget(t, obj.event_id).then(res => {
                    global.refreshWindow()
                    setShowPicker(false)
                })
                return;
            }
        }
        else if (selItem.event == 'SLEEP_WAKE_UP') {
            const obj = health.windows.sleep_active.sleep.timeline[0]
            if (obj.action == 'POST_MOMENT' || obj.action == 'NA') {
                const format = dayjs(obj.target.timestamp).format(`YYYY-MM-DDT${strTime}:ss`)
                var t = new Date(format).getTime()
                if (t <= obj.target.timestamp) {
                    t += 24 * 3600 * 1000
                }
                updateTarget(t, obj.event_id).then(res => {
                    global.refreshWindow()
                    setShowPicker(false)
                })
                return;
            }
        }
        console.log('zzz')

        updateSchedule({
            time: strTime
        }, selItem.schedule_id).then(res => {
            global.refreshWindow()
            setShowPicker(false)
        })
    }

    function modalContent() {
        global.set_time = new Date().getTime()
        return <Modal
            testInfo={null}
            dismiss={() => {
                setShowTimePicker(false)
            }}
            confirm={() => { }}>
            {
                timePickerContent()
            }
        </Modal>
    }

    function timePickerContent() {
        var title, color;
        switch (selItem.scenario) {
            case 'FAST':
                title = operateType == 'endFast' ? '结束断食' : '开始断食'
                color = MainColorType.fast
                break;
            case 'SLEEP':
                title = operateType == 'endFast' ? '结束睡眠' : '开始睡眠'
                color = MainColorType.sleep
        }

        var endTimestamp = 0
        if (operateType == 'endFast') {
            endTimestamp = new Date().getTime()//fastData.target.end_time
        }

        var duration = 24 * 3600 * 1000//fastData.target.duration

        return <View className="modal_content">
            <ConsolePicker ref={limitPickerRef}
                themeColor={color}
                title={title}
                onCancel={() => {
                    setShowTimePicker(false)
                }}
                min={min}
                max={max}
                current={defaultTimestamp}
                duration={duration}
                endTimestamp={endTimestamp}
                isFast={true}
                isEnd={operateType == 'endFast'}
                isTimeout={false}
                isLoading={btnDisable}
                onChange={(e) => {
                    pickerConfirm(e, null)
                    global.pauseIndexTimer = false
                }}
            />
        </View>
    }

    function pickerConfirm(t1: number, event: any) {
        if (btnDisable) {
            return
        }
        global.scenario = 'FAST'
        setBtnDisable(true)
        clockTimes({
            check_items: [{
                schedule_id: selItem.schedule_id,
                date: dayjs(t1).format('YYYYMMDD'),
                timestamp: t1
            }]
        }).then(res => {
            setBtnDisable(false)
            setShowTimePicker(false)
            global.refreshWindow()
        }).catch(e => {
            setBtnDisable(false)
        })
    }

    function more() {
        showActionSheet({
            showActionSheetWithOptions: showActionSheetWithOptions,
            title: 'Oprate Title',
            itemList: [
                'Add Snack',
                '自定义餐次列表',
            ],
            success: (res) => {
                switch (res) {
                    case 0:
                        break;
                    case 1:
                        jumpPage('/_eat/pages/meal_list')
                        break;
                }
            }
        });
    }

    function getThemeColor() {
        switch (health.mode) {
            case 'DAY':
                return MainColorType.day;
            case 'NIGHT':
                return MainColorType.night;
            case 'FAST':
                return MainColorType.fast;
            case 'EAT':
                return MainColorType.eat;
            case 'SLEEP':
                return MainColorType.sleep;
            case 'ACTIVE':
                return MainColorType.active;
        }
    }

    function detail() {
        const { day, night } = health.windows.night_day
        const { fast, eat } = health.windows.fast_eat
        const { sleep, active } = health.windows.sleep_active
        let list: any = []
        switch (health.mode) {
            case 'DAY':
                list = day.timeline
                break;
            case 'NIGHT':
                list = night.timeline
                break;
            case 'FAST':
                list = fast.timeline
                break;
            case 'EAT':
                list = eat.timeline
                break;
            case 'SLEEP':
                list = sleep.timeline
                break;
            case 'ACTIVE':
                list = active.timeline
                break;
        }

        return <View>
            {
                list.map((item, index) => {
                    return timelineItem(item, index, list.length)
                })
            }
        </View>
    }

    function switchText() {
        switch (health.mode) {
            case 'FAST':
                return 'Switch to Eat'
            case 'EAT':
                return 'Switch to Fast'
            case 'DAY':
                return 'Switch to Night'
            case 'NIGHT':
                return 'Switch to Daylight'
            case 'SLEEP':
                return 'Switch to Activity'
            case 'ACTIVE':
                return 'Switch to Sleep'

        }
        return ''
    }

    function tapSwitchBtn() {
        switch (health.mode) {
            case 'FAST':
                dispatch(setMode('EAT'));
                break
            case 'EAT':
                dispatch(setMode('FAST'));
                break
            case 'DAY':
                dispatch(setMode('NIGHT'));
                break
            case 'NIGHT':
                dispatch(setMode('DAY'));
                break
            case 'SLEEP':
                dispatch(setMode('ACTIVE'));
                break
            case 'ACTIVE':
                dispatch(setMode('SLEEP'));
                break

        }
    }
    return <View className="main-console-bg">
        <Image className="main_arrow" src={require('@assets/images/center_arrow.png')} />
        <View className="main_summary">
            <View className="main_summary_status" style={{ color: getThemeColor() }}>{getWindowStatus(health.windows, health.mode)}</View>
            <Text className="main_summary_time">{getCountownTime(health.windows, health.mode)}</Text>
            <Text className="main_summary_duration">Total {getDuration(health.windows, health.mode)}</Text>
            <View className="border_footer_line" />
        </View>
        <View style={{ backgroundColor: '#fff', width: rpxToPx(750) }}>
            {
                detail()
            }
        </View>
        <View className="main_footer">
            <Text className="main_footer_text" onClick={tapSwitchBtn}>{switchText()}</Text>
        </View>
        {
            (health.mode == 'EAT' || health.mode == 'ACTIVE') && <Text style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={more}>更多</Text>
        }
        {
            showTimePicker && modalContent()
        }
        {
            showPicker && timeContent()
        }
    </View>
}