import { View, Text, Image } from "@tarojs/components";
import NewHeader, { NewHeaderType } from "../components/new_header";
import Card from "../components/card";
import './long_fast.scss'
import '@features/health/MainConsole.scss'
import { MainColorType } from "@/context/themes/color";
import { rpxToPx } from "@/utils/tools";
import NewButton, { NewButtonType } from "../base/new_button";
import { getScenario, getThemeColor } from "@/features/health/hooks/health_hooks";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import MainHistory from "@/features/health/MainHistory";
import { useSelector } from "react-redux";
import showAlert from "@/components/basic/Alert";
import { clockTimes, delRecord, updateFast } from "@/services/health";
import { useEffect, useState } from "react";
import { TimeFormatter } from "@/utils/time_format";
import dayjs from "dayjs";
import showActionSheet from "@/components/basic/ActionSheet";
import NewModal from "../base/new_modal";
import NewDurationPicker, { DurationPickerType } from "../base/new_durationpicker";
import Taro from "@tarojs/taro";
import { useTranslation } from "react-i18next";
import NewTimePicker from "../base/new_timepicker";

let useActionSheet;
if (process.env.TARO_ENV == 'rn') {
    useActionSheet = require('@expo/react-native-action-sheet').useActionSheet
}

export default function LongFast() {
    const health = useSelector((state: any) => state.health);
    const long_fast = health.long_fast
    const [count, setCount] = useState(1)
    const [editDuration, setEditDuration] = useState(false)
    const [showPicker, setShowPicker] = useState(false)
    const [duration, setDuration] = useState(0)
    const [time, setTime] = useState(dayjs().format('HH:mm'))
    const { t } = useTranslation()
    let showActionSheetWithOptions;
    if (process.env.TARO_ENV == 'rn') {
        showActionSheetWithOptions = useActionSheet()
    }

    useEffect(() => {
        var timer = setInterval(() => {
            setCount(count => count + 1)
        }, 1000)

        setDuration(health.long_fast.extra.long_fast_goal / 60)

        return () => {
            clearInterval(timer)
        }
    }, [])

    function tapStart() {
        const fast = getScenario(health.windows, 'FAST')
        if (fast.status == 'OG') {
            showAlert({
                title: '断食进行中',
                content: '当前有一个正在进行的间歇性断食记录，要转换为长断食吗？',
                showCancel: true,
                cancelText: '取消',
                confirmText: '转换',
                confirm: () => {
                    // 
                    updateFast({ fast_type: 'LF' }).then(res => {
                        global.refreshWindow()
                    })
                }
            })
        }
        else {
            jumpPage('./long_fast_setting')
        }
    }

    function tapLog() {
        var item = long_fast.timeline[0]
        const { event_id, schedule_id } = item
        jumpPage(`/_health/pages/timeline_detail?event_id=${event_id}&schedule_id=${schedule_id}`)
        // jumpPage(`/_health/pages/add_moment?moment=${JSON.stringify(item)}&title=${item.title}&schedule_id=${item.schedule_id}&event_id=${item.event_id}`)
    }

    function tapEnd() {
        // save()
        setShowPicker(true)
    }

    function tapMore() {
        var listItems = ['编辑目标', t('health.delete_current_record')]
        if (long_fast.status == 'OG') {
            listItems.push('结束断食')
            // listItems.push(t('health.edit_fast_goal'))
        }
        showActionSheet({
            title: t('health.more_actions'),
            showActionSheetWithOptions: showActionSheetWithOptions,
            itemList: listItems,
            success: (res) => {
                switch (res) {
                    case 0:
                        setEditDuration(true)
                        break
                    case 1:
                        showAlert({
                            title: '确定要放弃本次断食吗？',
                            content: '放弃后断食不会本记录',
                            showCancel: true,
                            cancelText: '取消',
                            confirmText: '确定',
                            confirm: () => {
                                del()
                            }
                        })
                        break;
                    case 2:
                        tapEnd()
                        break;
                }
            }
        })
    }

    function del() {
        delRecord(health.long_fast.window_id).then(res => {
            global.refreshWindow()
        })
    }

    function save(warn_code = null) {
        var date = new Date()
        date.setHours(parseInt(time.substring(0, 2)))
        date.setMinutes(parseInt(time.substring(3, 5)))
        var params: any = {
            check_items: [{
                schedule_id: long_fast.timeline[1].schedule_id,
                date: dayjs(date.getTime()).format('YYYYMMDD'),
                timestamp: date.getTime(),
                extra: {
                    set_time: global.set_time ? global.set_time : new Date().getTime(),
                    confirm_time: new Date().getTime()
                }
            }]
        }
        if (warn_code) {
            params.save_confirm = warn_code
        }

        clockTimes(params).then(res => {
            if ((res as any).warn_code == 'SAVE_AS_IF') {
                showAlert({
                    title: 'Saving as Intermittent Fasting',
                    content: 'Fasting that lasts fewer than 24 hours will be saved as Intermittent Fasting.',
                    showCancel: true,
                    cancelText: '取消',
                    confirmText: '保存',
                    cancel: () => {
                    },
                    confirm: () => {
                        save((res as any).warn_code)
                    }
                })
                return
            }
            global.refreshWindow()
            global.refreshHistory()
            jumpPage('/_health/pages/post_result?data=' + JSON.stringify(res))
        }).catch(e => {
        })
    }

    function timeText() {
        if (long_fast.status == 'OG') {
            return TimeFormatter.countdown(long_fast.real.start_timestamp)
        }
        return '00:00:00'
    }

    function goal() {
        var hours = long_fast.extra.long_fast_goal / 60
        return hours + '小时'
        // var days = Math.floor(hours / 24)
        // var left = hours % 24
        // var str = ''
        // if (days > 0) {
        //     str = days + '天'
        // }
        // if (left > 0) {
        //     str += left + '小时'
        // }
        // return str
    }

    function moment() {
        if (long_fast.timeline[0].moment) {
            const moment = long_fast.timeline[0].moment
            return <View style={{
                marginTop: rpxToPx(22), display: 'flex',
                flexDirection: 'row', alignItems: 'center',
                justifyContent: 'center',
            }}>
                {
                    moment.media && moment.media.length > 0 && <Image
                        src={moment.media[0].url}
                        mode="aspectFill"
                        style={{ width: rpxToPx(28), height: rpxToPx(28), borderRadius: rpxToPx(4) }} />
                }
                <Text className="h20" style={{ marginLeft: rpxToPx(12), color: MainColorType.g02 }}>{moment.description} · {TimeFormatter.dateDescription(moment.time.timestamp, true)}</Text>
                {/* <Text className="h20" style={{ marginLeft: rpxToPx(12), color: MainColorType.g02 }}></Text> */}
            </View>
        }
        return <View />
    }

    return <View className="page_container">
        <NewHeader type={NewHeaderType.left_subtitle}
            title="Long Fast "
            subtitle="Prolonged Fasting beyond 24 hours"
        />
        <Card>
            <View className="long_fast_card" >
                <View style={{ height: rpxToPx(96) }} />
                <View className="h50 bold" style={{ color: MainColorType.fast }}>{timeText()}</View>
                <View className="h24" style={{ color: MainColorType.g02, marginTop: rpxToPx(12) }}>Goal {goal()}</View>
                <View style={{ height: rpxToPx(44) }} />
                {
                    long_fast.status == 'WFS' ? <NewButton
                        type={NewButtonType.fill}
                        width={rpxToPx(538)}
                        height={rpxToPx(96)}
                        color={getThemeColor('FAST')}
                        title="Start fast"
                        onClick={() => {
                            tapStart()
                            // 
                        }}
                    /> :
                        <NewButton
                            type={NewButtonType.alpha}
                            width={rpxToPx(538)}
                            height={rpxToPx(96)}
                            color={getThemeColor('FAST')}
                            title="How are you feeling?"
                            onClick={() => {
                                tapLog()
                            }}
                        />
                }
                {
                    moment()
                }

            </View>
        </Card>
        {/* {
            long_fast.status == 'OG' && <View style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <NewButton
                    type={NewButtonType.link}
                    height={rpxToPx(96)}
                    title='End fast'
                    onClick={() => {
                        tapEnd()
                    }}
                />
            </View>
        }
        {
            long_fast.status == 'OG' && <Text onClick={tapMore}>More</Text>
        } */}

        <View className="long_fast_footer" style={{ backgroundColor: 'transparent', marginBottom: -rpxToPx(35) }}>
            <View style={{ width: rpxToPx(316), height: rpxToPx(128), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {
                    long_fast.status == 'OG' ? <NewButton
                        type={NewButtonType.link}
                        title={'End longfast'}
                        onClick={tapEnd}
                    >
                    </NewButton> : <NewButton
                        type={NewButtonType.link}
                        title={'See Guidelines'}
                        onClick={() => { }}
                    >
                    </NewButton>
                }
            </View>
            {
                long_fast.status == 'OG' && <NewButton
                    btnStyle={{
                        position: 'absolute',
                        top: rpxToPx(42),
                        right: rpxToPx(26)
                    }}
                    type={NewButtonType.more}
                    onClick={tapMore}
                />
            }


        </View>



        <MainHistory type='FAST' fast_type="LF" />

        {
            editDuration && <NewModal
                title='长断食时长'
                dismiss={() => {
                    setEditDuration(false)
                }}
                confirm={() => {

                    updateFast({ fast_type: 'LF', long_fast_goal: duration * 60 }).then(res => {
                        setEditDuration(false)
                        global.refreshWindow()
                    })
                }}
                themeColor={getThemeColor(health.mode)}>
                <View style={{ flexDirection: 'column', display: 'flex', alignItems: 'center', marginBottom: 20 }}>
                    <NewDurationPicker type={DurationPickerType.long}
                        color={MainColorType.fast}
                        value={duration}
                        onChange={e => setDuration(e)} />
                </View>
            </NewModal>
        }
        {
            showPicker && <NewModal
                title='结束长断食'
                dismiss={() => {
                    setShowPicker(false)
                }}
                confirm={() => {

                    save()
                }}
                themeColor={getThemeColor(health.mode)}>
                <View style={{ flexDirection: 'column', display: 'flex', alignItems: 'center', marginBottom: 20 }}>
                    <NewTimePicker
                        color={MainColorType.fast}
                        time={dayjs().format('HH:mm')}
                        onChange={e => setTime(e)} />
                </View>
            </NewModal>
        }
    </View>
}