import { View, Text, Image, PickerView, PickerViewColumn } from "@tarojs/components";
import { useTranslation } from "react-i18next";
import { AtActivityIndicator } from "taro-ui";
import { alphaToHex, rpxToPx } from "@/utils/tools";
import { ColorType } from "@/context/themes/color";
import "@/components/layout/Modal.scss";
import './IndexConsoleMuti.scss';
import { useRef, useState } from "react";
import { batchClocks, endFast, getLocalPush } from "../actions/TrackTimeActions";
import dayjs from "dayjs";
import Modal from "@/components/layout/Modal.weapp";
import ConsolePicker from "./ConsolePicker";
import Taro from "@tarojs/taro";
import { TimeFormatter } from "@/utils/time_format";

let min = 0
let max = 0
let defaultTimestamp = 0
export default function IndexConsoleMuti(props: { status: string, event: string, close: Function, scenario: string }) {
    const { t } = useTranslation();
    const isLoading = false;
    var color = ColorType.fast;
    var alpha = alphaToHex(0.4)
    const [fastStart, setFastStart] = useState<any>(null)
    const [fastEnd, setFastEnd] = useState<any>(null)
    const [sleepStart, setSleepStart] = useState<any>(null)
    const [sleepEnd, setSleepEnd] = useState<any>(null)
    const [showPicker, setShowPicker] = useState(false)
    const [operateType, setOperateType] = useState('startFast')
    const [commitLoading, setCommitLoading] = useState(false)
    const pickerRef = useRef(null)


    function cancel() {
        props.close()
    }

    function confirm() {
        if (commitLoading) {
            return;
        }
        var fast: any = {}
        var sleep: any = {}
        switch (props.event) {
            case 'start_sleep':
                if (!fastStart) {
                    Taro.showToast({
                        icon: 'none',
                        title: '请选择开始断食时间'
                    })
                    return
                }
                if (!sleepStart) {
                    Taro.showToast({
                        icon: 'none',
                        title: '请选择就寝时间'
                    })
                    return
                }
                // fast.real_start_set_time = fastStart.set_time
                // fast.real_start_confirm_time = fastStart.confirm_time
                // fast.real_start_time = fastStart.time
                // fast.real_start_date = fastStart.date
                // sleep.real_start_set_time = sleepStart.set_time
                // sleep.real_start_confirm_time = sleepStart.confirm_time
                // sleep.real_start_time = sleepStart.time
                // sleep.real_start_date = sleepStart.date

                fast.real_start = {
                    time: fastStart.time,
                    date: fastStart.date,
                    extra: {
                        set_time: fastStart.set_time,
                        confirm_time: fastStart.confirm_time
                    }
                }
                sleep.real_start = {
                    time: sleepStart.time,
                    date: sleepStart.date,
                    extra: {
                        set_time: sleepStart.set_time,
                        confirm_time: sleepStart.confirm_time
                    }
                }
                break;
            case 'end_sleep':
                if (props.status == 'WAIT_FOR_START') {
                    if (!fastStart) {
                        Taro.showToast({
                            icon: 'none',
                            title: '请选择开始断食时间'
                        })
                        return
                    }
                    // fast.real_start_set_time = fastStart.set_time
                    // fast.real_start_confirm_time = fastStart.confirm_time
                    // fast.real_start_time = fastStart.time
                    // fast.real_start_date = fastStart.date

                    fast.real_start = {
                        time: fastStart.time,
                        date: fastStart.date,
                        extra: {
                            set_time: fastStart.set_time,
                            confirm_time: fastStart.confirm_time
                        }
                    }
                }
                if (!sleepStart) {
                    Taro.showToast({
                        icon: 'none',
                        title: '请选择就寝时间'
                    })
                    return
                }
                if (!sleepEnd) {
                    Taro.showToast({
                        icon: 'none',
                        title: '请选择起床时间'
                    })
                    return
                }
                // sleep.real_start_set_time = sleepStart.set_time
                // sleep.real_start_confirm_time = sleepStart.confirm_time
                // sleep.real_start_time = sleepStart.time
                // sleep.real_start_date = sleepStart.date
                // sleep.real_end_set_time = sleepEnd.set_time
                // sleep.real_end_confirm_time = sleepEnd.confirm_time
                // sleep.real_end_time = sleepEnd.time
                // sleep.real_end_date = sleepEnd.date

                sleep.real_start = {
                    time: sleepStart.time,
                    date: sleepStart.date,
                    extra: {
                        set_time: sleepStart.set_time,
                        confirm_time: sleepStart.confirm_time
                    }
                }

                sleep.real_end = {
                    time: sleepEnd.time,
                    date: sleepEnd.date,
                    extra: {
                        set_time: sleepEnd.set_time,
                        confirm_time: sleepEnd.confirm_time
                    }
                }
                break;
            case 'end_fast':
                if (props.status == 'WAIT_FOR_START') {
                    if (!fastStart) {
                        Taro.showToast({
                            icon: 'none',
                            title: '请选择开始断食时间'
                        })
                        return
                    }
                    if (!sleepStart && props.scenario == 'FAST_SLEEP') {
                        Taro.showToast({
                            icon: 'none',
                            title: '请选择就寝时间'
                        })
                        return
                    }
                    // fast.real_start_set_time = fastStart.set_time
                    // fast.real_start_confirm_time = fastStart.confirm_time
                    // fast.real_start_time = fastStart.time
                    // fast.real_start_date = fastStart.date

                    fast.real_start = {
                        time: fastStart.time,
                        date: fastStart.date,
                        extra: {
                            set_time: fastStart.set_time,
                            confirm_time: fastStart.confirm_time
                        }
                    }

                    if (props.scenario == 'FAST_SLEEP') {
                        // sleep.real_start_set_time = sleepStart.set_time
                        // sleep.real_start_confirm_time = sleepStart.confirm_time
                        // sleep.real_start_time = sleepStart.time
                        // sleep.real_start_date = sleepStart.date
                        sleep.real_start = {
                            time: sleepStart.time,
                            date: sleepStart.date,
                            extra: {
                                set_time: sleepStart.set_time,
                                confirm_time: sleepStart.confirm_time
                            }
                        }
                    }


                }
                else if (props.status == 'ONGOING1') {
                    if (!sleepStart) {
                        Taro.showToast({
                            icon: 'none',
                            title: '请选择就寝时间'
                        })
                        return
                    }
                    // sleep.real_start_set_time = sleepStart.set_time
                    // sleep.real_start_confirm_time = sleepStart.confirm_time
                    // sleep.real_start_time = sleepStart.time
                    // sleep.real_start_date = sleepStart.date
                    sleep.real_start = {
                        time: sleepStart.time,
                        date: sleepStart.date,
                        extra: {
                            set_time: sleepStart.set_time,
                            confirm_time: sleepStart.confirm_time
                        }
                    }
                }
                if (!sleepEnd && props.scenario == 'FAST_SLEEP') {
                    Taro.showToast({
                        icon: 'none',
                        title: '请选择起床时间'
                    })
                    return
                }
                if (!fastEnd) {
                    Taro.showToast({
                        icon: 'none',
                        title: '请选择结束断食时间'
                    })
                    return
                }

                if (props.scenario == 'FAST_SLEEP') {
                    // sleep.real_end_set_time = sleepEnd.set_time
                    // sleep.real_end_confirm_time = sleepEnd.confirm_time
                    // sleep.real_end_time = sleepEnd.time
                    // sleep.real_end_date = sleepEnd.date
                    sleep.real_end = {
                        time: sleepEnd.time,
                        date: sleepEnd.date,
                        extra: {
                            set_time: sleepEnd.set_time,
                            confirm_time: sleepEnd.confirm_time
                        }
                    }
                }
                // fast.real_end_set_time = fastEnd.set_time
                // fast.real_end_confirm_time = fastEnd.confirm_time
                // fast.real_end_time = fastEnd.time
                // fast.real_end_date = fastEnd.date
                fast.real_end = {
                    time: fastEnd.time,
                    date: fastEnd.date,
                    extra: {
                        set_time: fastEnd.set_time,
                        confirm_time: fastEnd.confirm_time
                    }
                }
                break;
        }

        setCommitLoading(true)
        var params: any = {
        }
        if (props.scenario == 'FAST_SLEEP') {
            params = {
                fast,
                sleep
            }
        }
        else {
            params = {
                fast
            }
        }
        params.showAlert = true
        batchClocks(params).then(res => {
            setCommitLoading(false)
            getLocalPush()
            global.indexPageRefresh()
            if ((res as any).current_record.status == "WAIT_FOR_START") {
                global.scrollToLatest()
                global.swiperDayNightRefresh()
                if (global.refreshNight) {
                    global.refreshNight()
                }
                if (global.refreshDay) {
                    global.refreshDay()
                }
            }

            global.refrehWeekly()
            global.refreshStreaks()
            if (props.event == 'end_fast')
                global.checkAccess((res as any).access)

            cancel()
        }).catch(e => {
            setCommitLoading(false)
        })
    }

    function tapItem(index: number) {
        setShowPicker(true);
        switch (index) {
            case 0:
                setOperateType('startFast')
                break;
            case 1:
                setOperateType('startSleep')
                break;
            case 2:
                setOperateType('endSleep')
                break;
            case 3:
                setOperateType('endFast')
                break;
        }
    }

    function startFastCell() {
        return <View className="new_item_cell" onClick={() => tapItem(0)}>
            <Text className="new_item_cell_title">{t('feature.track_time_duration.common.start_fast')}</Text>
            <View style={{ flex: 1 }} />
            <Text className="new_item_cell_desc">{fastStart ? TimeFormatter.dateTimeFormate(fastStart.time, true) : t('feature.track_time_duration.log_timing.pick_time')}</Text>
            <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
        </View>
    }

    function startSleepCell() {
        return <View className="new_item_cell" onClick={() => tapItem(1)}>
            <Text className="new_item_cell_title">{t('feature.track_time_duration.common.start_sleep')}</Text>
            <View style={{ flex: 1 }} />
            <Text className="new_item_cell_desc">{sleepStart ? TimeFormatter.dateTimeFormate(sleepStart.time, true) : t('feature.track_time_duration.log_timing.pick_time')}</Text>
            <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
        </View>
    }

    function endSleepCell() {
        return <View className="new_item_cell" onClick={() => tapItem(2)}>
            <Text className="new_item_cell_title">{t('feature.track_time_duration.common.end_sleep')}</Text>
            <View style={{ flex: 1 }} />
            <Text className="new_item_cell_desc">{sleepEnd ? TimeFormatter.dateTimeFormate(sleepEnd.time, true) : t('feature.track_time_duration.log_timing.pick_time')}</Text>
            <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
        </View>
    }

    function endFastCell() {
        return <View className="new_item_cell" onClick={() => tapItem(3)}>
            <Text className="new_item_cell_title">{t('feature.track_time_duration.common.end_fast')}</Text>
            <View style={{ flex: 1 }} />
            <Text className="new_item_cell_desc">{fastEnd ? TimeFormatter.dateTimeFormate(fastEnd.time, true) : t('feature.track_time_duration.log_timing.pick_time')}</Text>
            <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />
        </View>
    }

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

    function timePickerContent() {
        defaultTimestamp = new Date().getTime()
        min = defaultTimestamp - 1 * 24 * 3600 * 1000
        max = defaultTimestamp
        global.pauseIndexTimer = true
        var title = t('feature.track_time_duration.console.real_fast_start_dt')
        if (operateType == 'endFast') {
            title = t('feature.track_time_duration.console.real_fast_end_dt')
        }
        else if (operateType == 'startSleep') {
            title = t('feature.track_time_duration.console.real_sleep_start_dt')
        }
        else if (operateType == 'endSleep') {
            title = t('feature.track_time_duration.console.real_sleep_end_dt')
        }

        var color = operateType == 'startFast' || operateType == 'endFast' ? ColorType.fast : ColorType.sleep
        var endTimestamp = min


        var duration = 20000

        return <View className="modal_content">

            <ConsolePicker ref={pickerRef}
                themeColor={color}
                title={title}
                onCancel={() => {
                    setShowPicker(false)
                    global.pauseIndexTimer = false
                }}
                min={min}
                max={max}
                current={defaultTimestamp}
                duration={duration}
                endTimestamp={endTimestamp}
                isFast={operateType == 'startFast' || operateType == 'endFast'}
                isEnd={operateType == 'endFast' || operateType == 'endSleep'}
                isTimeout={false}
                isLoading={false}
                hidenEndTime={true}
                onChange={(e) => {
                    setShowPicker(false)
                    global.pauseIndexTimer = false
                    if (operateType == 'startFast') {
                        setFastStart({
                            set_time: defaultTimestamp,
                            confirm_time: new Date().getTime(),
                            time: e,
                            date: dayjs(e).format('YYYYMMDD')
                        })
                    }
                    else if (operateType == 'endFast') {
                        setFastEnd({
                            set_time: defaultTimestamp,
                            confirm_time: new Date().getTime(),
                            time: e,
                            date: dayjs(e).format('YYYYMMDD')
                        })
                    }
                    else if (operateType == 'startSleep') {
                        setSleepStart({
                            set_time: defaultTimestamp,
                            confirm_time: new Date().getTime(),
                            time: e,
                            date: dayjs(e).format('YYYYMMDD')
                        })
                    }
                    else {
                        setSleepEnd({
                            set_time: defaultTimestamp,
                            confirm_time: new Date().getTime(),
                            time: e,
                            date: dayjs(e).format('YYYYMMDD')
                        })
                    }
                }}
            />

        </View>
    }

    return <View className="modal_content">
        <View style={{
            marginLeft: rpxToPx(46),
            height: rpxToPx(120), display: 'flex',
            flexDirection: 'row', alignItems: 'center',
            marginTop: rpxToPx(36),
            marginBottom: rpxToPx(48)
        }}>
            <Text style={{ color: '#fff', fontWeight: 'bold', fontSize: rpxToPx(48) }}>{t('feature.track_time_duration.log_timing.log_timings')}</Text>
        </View>

        <View style={{
            display: 'flex',
            flexDirection: 'column',
            backgroundColor: '#262626',
            borderRadius: rpxToPx(24),
            marginLeft: rpxToPx(46),
            marginRight: rpxToPx(46),
            marginBottom: rpxToPx(60)

        }}>
            {
                props.event == 'start_sleep' && startFastCell()
            }
            {
                props.event == 'start_sleep' && <View className="new_item_cell_line" />
            }
            {
                props.event == 'start_sleep' && startSleepCell()
            }
            {
                props.event == 'end_sleep' && props.status == 'WAIT_FOR_START' && startFastCell()
            }
            {
                props.event == 'end_sleep' && props.status == 'WAIT_FOR_START' && <View className="new_item_cell_line" />
            }
            {
                props.event == 'end_sleep' && startSleepCell()
            }
            {
                props.event == 'end_sleep' && <View className="new_item_cell_line" />
            }
            {
                props.event == 'end_sleep' && endSleepCell()
            }
            {
                props.event == 'end_fast' && props.status == 'WAIT_FOR_START' && startFastCell()
            }
            {
                props.event == 'end_fast' && props.status == 'WAIT_FOR_START' && <View className="new_item_cell_line" />
            }
            {
                props.event == 'end_fast' && props.scenario == 'FAST_SLEEP' && (props.status == 'ONGOING1' || props.status == 'WAIT_FOR_START') && startSleepCell()
            }
            {
                props.event == 'end_fast' && props.scenario == 'FAST_SLEEP' && (props.status == 'ONGOING1' || props.status == 'WAIT_FOR_START') && <View className="new_item_cell_line" />
            }
            {
                props.event == 'end_fast' && props.scenario == 'FAST_SLEEP' && (props.status == 'ONGOING1' || props.status == 'ONGOING2' || props.status == 'WAIT_FOR_START') && endSleepCell()
            }
            {
                props.event == 'end_fast' && props.scenario == 'FAST_SLEEP' && (props.status == 'ONGOING1' || props.status == 'ONGOING2' || props.status == 'WAIT_FOR_START') && <View className="new_item_cell_line" />
            }
            {
                props.event == 'end_fast' && endFastCell()
            }
        </View>

        <View className='modal_operate'>

            <View className='modal_btn' style={{ backgroundColor: color + alpha }} onClick={cancel}>
                <Text className='modal_cancel_text' style={{ color: color, fontWeight: 'bold' }}>{t('feature.common.picker_cancel_btn')}</Text>
            </View>
            <View className='btn_space' />
            <View className='modal_btn' style={{ backgroundColor: color, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', opacity: commitLoading ? 0.6 : 1 }} onClick={confirm}>
                {
                    commitLoading && <View style={{ display: 'flex', overflow: 'hidden', height: 20, marginRight: 5 }}><AtActivityIndicator mode="center" color="#000" /></View>
                }

                <Text className='modal_confirm_text' style={{ color: '#000', fontWeight: 'bold' }}>{t('feature.common.picker_confirm_btn')}</Text>
            </View>


        </View>
        {
            showPicker && modalContent()
        }
    </View>
}