import { WindowType } from "@/utils/types";
import { View, Text } from "@tarojs/components";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { 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 } from "@/services/health";

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 [showTimePicker, setShowTimePicker] = useState(false)
    const [operateType, setOperateType] = useState('')
    const [btnDisable, setBtnDisable] = useState(false)
    const [selItem, setSelItem] = useState<any>(null)
    const limitPickerRef = useRef(null)

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


    useEffect(() => {

    }, [props.type])


    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 timelineItem(item: any, index: number) {
        return <View key={index} className="timeline_item" >
            <View className="timeline_left">
                <Text className="timeline_title">{item.title}</Text>
                <Text className="timeline_time">{dayjs(item.target.timestamp).format('HH:mm')}</Text>
            </View>
            {
                item.action && item.action != 'NA' && <View className="timeline_operate" onClick={() => record(item)}>记录</View>
            }

        </View>
    }

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

    function timePickerContent() {
        var title = operateType == 'endFast' ? '结束断食' : '开始断食'
        var color = MainColorType.fast
        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 detail() {
        const { day, night } = health.windows.night_day
        const { fast, eat } = health.windows.fast_eat
        const { sleep, active } = health.windows.sleep_active
        switch (health.mode) {
            case 'DAY':
                return <View>
                    {
                        day.timeline.map((item, index) => {
                            return timelineItem(item, index)
                        })
                    }
                </View>
            case 'NIGHT':
                return <View>
                    {
                        night.timeline.map((item, index) => {
                            return timelineItem(item, index)
                        })
                    }
                </View>
            case 'FAST':
                return <View>
                    {
                        fast.timeline.map((item, index) => {
                            return timelineItem(item, index)
                        })
                    }
                </View>
            case 'EAT':
                return <View>
                    {
                        eat.timeline.map((item, index) => {
                            return timelineItem(item, index)
                        })
                    }
                </View>
            case 'SLEEP':
                return <View>
                    {
                        sleep.timeline.map((item, index) => {
                            return timelineItem(item, index)
                        })
                    }
                </View>
            case 'ACTIVE':
                return <View>
                    {
                        active.timeline && active.timeline.map((item, index) => {
                            return timelineItem(item, index)
                        })
                    }
                </View>
        }
        return <View />
    }
    return <View>
        {
            detail()
        }
        {
            showTimePicker && modalContent()
        }
    </View>
}