import { View, Text, Image } from "@tarojs/components";
import './fast_sleep_console.scss'
import { rpxToPx } from "@/utils/tools";
import NewButton, { NewButtonType } from "../base/new_button";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import dayjs from "dayjs";
import { MainColorType } from "@/context/themes/color";
import showAlert from "@/components/basic/Alert";
import { IconArrow, IconCellArrow, IconCircle, IconError, IconNotification, IconNotificationOff } from "@/components/basic/Icons";
import { useSelector } from "react-redux";
import { delRecord } from "@/services/health";
import { TimeFormatter } from "@/utils/time_format";
import showActionSheet from "@/components/basic/ActionSheet";
import { useTranslation } from "react-i18next";
import ConsoleCell from "./console_cell";
import StatusIndicator, { StatusType } from "../base/status_indicator";

export default function FastSleepConsole(props: { step: number, data: any, del: any }) {
    const health = useSelector((state: any) => state.health);
    let navigation, showActionSheetWithOptions;
    const { t } = useTranslation()
    function tapLogBtn(index: number) {
        const { fast, sleep, status } = props.data
        var single = 0;
        var is_start = 0;
        var window = 'FAST'

        switch (index) {
            case 0:
                {
                    single = 1;
                    is_start = 1;
                }
                break;
            case 1:
                {
                    if (status == 'OG1') {
                        single = 1;
                        is_start = 1;
                        window = 'SLEEP'
                    }
                    else {
                        single = 0;
                    }
                }
                break;
            case 2:
                {
                    if (status == 'OG2') {
                        single = 1;
                        is_start = 0;
                        window = 'SLEEP'
                    }
                    else {
                        single = 0;
                    }
                }
                break;
            case 3:
                {
                    if (status == 'OG3') {
                        single = 1;
                        is_start = 0;
                        window = 'FAST'
                    }
                    else {
                        single = 0;
                    }
                }
                break;
        }

        jumpPage(`/_health/pages/log_time?is_fast_with_sleep=1&index=${index}&initCheck=${health.fast_with_sleep.status == 'OG2_MISALIGNED' ? 1 : 0}&single=${index == 0 ? 1 : 0}&is_start=${is_start}&window=${window}`)
        /*
            const isSingle = router.params.single == '1'
    const isFast = router.params.window == 'FAST'
    const isStart = router.params.is_start == '1'
    */
    }

    function goDetail(index) {
        if (index == 0 && props.data.fast.status == 'OG') {
            const { event_id, schedule_id } = props.data.fast.timeline[0]
            jumpPage(`/_health/pages/timeline_detail?event_id=${event_id}&schedule_id=${schedule_id}`)
        }
        else if (index == 1 && (props.data.sleep.status == 'OG' || props.data.status == 'OG3')) {
            const { event_id, schedule_id } = props.data.sleep.timeline[0]
            jumpPage(`/_health/pages/timeline_detail?event_id=${event_id}&schedule_id=${schedule_id}`)
        }

    }

    function itemDisableStatus(index) {
        if (index == 0 && props.data.fast.status == 'OG') {
            return false
        }
        else if (index == 1 && (props.data.sleep.status == 'OG' || props.data.status == 'OG3')) {
            return false
        }
        return true
    }

    function delConfirm() {
        const { fast, sleep } = props.data
        let array: any = []
        if (fast.window_id) {
            array.push(fast.window_id)
        }
        if (sleep.window_id) {
            array.push(sleep.window_id)
        }


        showAlert({
            title: 'del',
            content: '确认删除此记录?',
            showCancel: true,
            confirm: () => {
                delRecord(array[0], { ids: array }).then(res => {
                    global.refreshWindow()
                    props.del()
                })
            }
        })
    }

    function getIconColor(index: number, finish: boolean) {
        const { fast, sleep } = props.data
        // if (new Date().getTime() <= fast.target.start_timestamp && health.fast_with_sleep.status == 'WFS') {
        //     return MainColorType.g03
        // }
        switch (index) {
            case 0:
                if (!fast.timeline[0].real) {
                    return MainColorType.g02
                }
                break
            case 1:
                if (!sleep.timeline[0].real) {
                    return MainColorType.g02
                }
                break
            case 2:
                if (!sleep.timeline[1].real) {
                    return MainColorType.g02
                }
                break
            case 3:
                if (!fast.timeline[1].real) {
                    return MainColorType.g02
                }
                break
        }
        var color = MainColorType.g02
        if (index == 1 || index == 2) {
            color = MainColorType.sleep
        }
        else {
            color = MainColorType.fast
        }
        return color;
    }

    function processIcon(item, finish, isError) {
        if (isError) {
            return <IconError color="#fff" width={rpxToPx(24)} />
        }
        if (finish) {
            return <Image style={{ width: rpxToPx(24), height: rpxToPx(24) }} src={require('@assets/_health/checked.png')} />
        }
        return <IconCircle width={rpxToPx(32)} color={MainColorType.g02}/>
        // return <View style={{ width: rpxToPx(26), height: rpxToPx(26), borderRadius: rpxToPx(13), backgroundColor: '#fff' }} />
        // if (item.timeline.reminder) {
        //     return <IconNotification color="#fff" width={rpxToPx(24)} />
        // }
        // return <IconNotificationOff color="#fff" width={rpxToPx(24)} />
    }

    function actionList() {
        var list: any = []
        if (!health.finish_setup) {
            list.push(t('health.finish_setup'))
        }
        if (props.data.status != 'WFS') {
            list.push(t('health.delete_current_record'))
        }
        if (health.finish_setup) {
            list.push(t('health.edit_schedule'))
        }
        return list
    }

    function showAction() {
        showActionSheet({
            showActionSheetWithOptions: showActionSheetWithOptions,
            title: t('health.more_actions'),
            itemList: actionList(),
            success: (res) => {
                tapActionSheet(res)
            }
        });
    }

    function tapActionSheet(index) {
        var title = actionList()[index]
        switch (title) {
            case t('health.finish_setup'):
                jumpPage('/_health/pages/guide_begin')
                break;
            case t('health.delete_current_record'):
                delConfirm()
                break;
            case t('health.edit_schedule'):
                jumpPage('/_health/pages/schedules?mode=FAST&isFastSleep=1')
                break
        }
    }


    function timelineItem(item: any, index: number, count: number) {
        const { fast, sleep, status } = props.data
        var showBtn = true;
        var time = ''
        var hasDescription = item.moment && item.moment.description
        var finish = false;

        switch (index) {
            case 0:
                {
                    if (status == 'OG2_NO1' || status == 'WFS') {
                        showBtn = true
                    }
                    else {
                        showBtn = false;
                        finish = true;
                    }
                    time = TimeFormatter.dayjsFormat(fast.target.start_timestamp)//dayjs(fast.target.start_timestamp).format('MM-DD HH:mm')
                }
                break;
            case 1:
                {
                    if (status == 'WFS' || status == 'OG1') {
                        showBtn = true
                    }
                    else {
                        showBtn = false
                        finish = true;
                    }
                    if (status == 'OG3') {
                        time = TimeFormatter.dayjsFormat(sleep.real.start_timestamp)//dayjs(sleep.real.start_timestamp).format('MM-DD HH:mm')
                    }
                    else {
                        time = TimeFormatter.dayjsFormat(sleep.target.start_timestamp)//dayjs(sleep.target.start_timestamp).format('MM-DD HH:mm')
                    }

                }
                break;
            case 2:
                {
                    if (status == 'OG3') {
                        showBtn = false
                        finish = true;
                        time = TimeFormatter.dayjsFormat(sleep.real.end_timestamp)//dayjs(sleep.real.end_timestamp).format('MM-DD HH:mm')
                    }
                    else {
                        showBtn = true
                        time = TimeFormatter.dayjsFormat(sleep.target.end_timestamp)//dayjs(sleep.target.end_timestamp).format('MM-DD HH:mm')
                    }

                }
                break;
            case 3:
                {
                    showBtn = true
                    time = TimeFormatter.dayjsFormat(fast.target.end_timestamp)//dayjs(fast.target.end_timestamp).format('MM-DD HH:mm')
                }
                break;
        }
        var isError = false;
        if (health.fast_with_sleep.status == 'OG2_MISALIGNED' && (index == 0 || index == 1)) {
            isError = true;
        }

        function rightView() {
            if (isError) {
                return <View style={{
                    borderColor: MainColorType.error,
                    borderWidth: rpxToPx(2),
                    borderRadius: rpxToPx(76 / 4),
                    borderStyle: 'solid'
                }}>
                    <NewButton
                        type={NewButtonType.gray}
                        title='Correct'
                        // fontSize={rpxToPx(34)}
                        width={rpxToPx(128)}
                        height={rpxToPx(72)}
                        onClick={() => {
                            jumpPage(`/_health/pages/log_time?is_fast_with_sleep=1&index=${1}&single=0&initCheck=1&initIndex=${index}`)
                        }}
                    />
                </View>
            }
            else {
                // let themeColor: any = getThemeColor(health.mode)
                // if (item.target.timestamp >= new Date().getTime()) {
                //     themeColor = MainColorType.g02
                // }
                if (item.timeline.action && item.timeline.action != 'NA') {

                    if (item.timeline.action == 'POST_MOMENT') {
                        return <IconArrow width={rpxToPx(34)} color={MainColorType.g03} />
                    }
                    return <NewButton
                        color={item.timeline.target.timestamp >= new Date().getTime() ? MainColorType.g02 : getThemeColor(item.mode)}
                        type={item.timeline.target.timestamp >= new Date().getTime() ? NewButtonType.alpha2 : NewButtonType.alpha}
                        title={t('health.log')}
                        width={rpxToPx(128)}
                        height={rpxToPx(72)}
                        bold={true}
                        onClick={() => {
                            tapLogBtn(index)
                        }} />
                }

                if (item.timeline.action && item.timeline.action == 'NA') {
                    // if (health.mode == 'FAST' || health.mode == 'SLEEP') {
                    if (item.moment && item.moment.media && item.moment.media.length > 0) {
                        return <Image
                            src={item.moment.media[0].url}
                            mode="aspectFill"
                            className="console_item_img" />
                    }
                    else {
                        return <IconArrow width={rpxToPx(34)} color={MainColorType.g03} />
                    }

                    // }
                }

                return <View />
                // if (item.timeline.action == 'POST_MOMENT'){
                //     return <IconArrow color={MainColorType.g03} width={rpxToPx(34)} />
                // }

                // if (item.moment && item.moment.media && item.moment.media.length > 0)
                //     return <Image
                //         src={item.moment.media[0].url}
                //         mode="aspectFill"
                //         className="console_item_img" />
                // if (showBtn)
                //     return <NewButton
                //         color={item.timeline.target.timestamp >= new Date().getTime() ? MainColorType.link : getThemeColor(item.mode)}
                //         type={item.timeline.target.timestamp >= new Date().getTime() ? NewButtonType.alpha2 : NewButtonType.alpha}
                //         title={'Log'}
                //         width={rpxToPx(128)}
                //         height={rpxToPx(72)}
                //         bold={true}
                //         onClick={() => {
                //             tapLogBtn(index)
                //         }} />
            }
        }

        return <ConsoleCell
            status={
                <StatusIndicator type={StatusType.console}
                    color={isError ? MainColorType.error : getIconColor(index, finish)==MainColorType.g02?'transparent':getIconColor(index, finish)}
                    fontColor={isError ? MainColorType.error : getIconColor(index, finish)==MainColorType.g02?MainColorType.g01:getIconColor(index, finish)}
                    bold={getIconColor(index, finish)!=MainColorType.g02}
                    fontSize={rpxToPx(24)}
                    text={time}
                >{
                        processIcon(item, finish, isError)
                    }</StatusIndicator>
            }
            title={(item.moment && item.moment.title) ? item.moment.title : item.title}
            description={hasDescription ? item.moment.description : null}
            disable={itemDisableStatus(index)}
            onClick={() => {
                goDetail(index)
            }}
            right={rightView()}
            showLine={true}
            fullLine={count - 1 == index}
        />
    }

    return <View style={{ backgroundColor: '#fff' }}>
        {
            health.fast_with_sleep.status == 'OG2_MISALIGNED' && <View className="error_bg" >
                <View className="error_icon_bg">
                    <Image src={require('@assets/_health/tip_error.png')} style={{ width: rpxToPx(26), height: rpxToPx(26) }} />
                </View>
                <Text className="h24" style={{ lineHeight: rpxToPx(36) + 'px' }}>Logged times are not in their proper order</Text>
            </View>
        }
        {
            props.step != 2 && props.step != 3 && timelineItem({
                title: props.data.fast.timeline[0].title,
                mode: 'FAST',
                is_start: true,
                action: props.data.fast.timeline[0].action,
                moment: props.data.fast.timeline[0].moment,
                timeline: props.data.fast.timeline[0]
            }, 0, 4)
        }
        {
            props.step != 3 && timelineItem({
                title: props.data.sleep.timeline[0].title,
                mode: 'SLEEP',
                is_start: true,
                action: props.data.fast.timeline[0].action,
                moment: props.data.sleep.timeline[0].moment,
                timeline: props.data.sleep.timeline[0]
            }, 1, 4)
        }
        {
            props.step != 1 && timelineItem({
                title: props.data.sleep.timeline[1].title,
                mode: 'SLEEP',
                is_start: false,
                moment: props.data.sleep.timeline[1].moment,
                timeline: props.data.sleep.timeline[1]
            }, 2, 4)
        }
        {
            props.step != 1 && props.step != 2 && timelineItem({
                title: props.data.fast.timeline[1].title,
                mode: 'FAST',
                is_start: false,
                moment: props.data.fast.timeline[1].moment,
                timeline: props.data.fast.timeline[1]
            }, 3, 4)
        }
        {
            <View className="main_console_footer">
                <NewButton
                    btnStyle={{
                        position: 'absolute',
                        top: rpxToPx(42),
                        right: rpxToPx(40)
                    }}
                    type={NewButtonType.more}
                    onClick={showAction}
                />

            </View>
        }


    </View>
}