import { View, Text } from "@tarojs/components";
import trackTimeService, { machine } from "@/store/trackTimeMachine"
import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import Box from "@/components/layout/Box";
import './Schedule.scss'
import { useTranslation } from "react-i18next";
import TimelineFastSleep from "./TimelineFastSleep";
import Switch from "@/components/input/Switch";
import { useDispatch, useSelector } from "react-redux";
import { TimeFormatter } from "@/utils/time_format";
import Buttons from "@/components/basic/Buttons";
import { ButtonType, ModalType } from "@/utils/types";
import { setStep } from "@/store/scenario";
import Segment from "@/components/navigation/Segment";
import Modal from "@/components/layout/Modal";
import Stage from "./Stage";
import CenterContentTitleModal from "@/features/common/CenterContentTitleModal";
import { ColorType } from "@/context/themes/color";
import { getThemeColor, jumpPage } from "../hooks/Common";
import TableCell from "@/components/layout/TableCell";
import TimelineStage from "./TimelineStage";


export default function Component(props: { type?: string, data?: any, delSuccess?: Function }) {
    const { t } = useTranslation()
    const permission = useSelector((state: any) => state.permission);
    const common = useSelector((state: any) => state.common);
    const time = useSelector((state: any) => state.time);
    const [showModal, setShowModal] = useState(false)
    const dispatch = useDispatch();

    function all() {
        if (props.type == 'latest') {
            jumpPage('/pages/common/RecordsHistory?type=time&title=Time')
        }
    }

    function showStage(e) {
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }
        setShowModal(true)
    }

    function followWxPub() {
        const resource = common.resources.filter((item: any) => {
            return item.code == 'follow_wx_pub'
        })

        const title = permission.wxPubFollow ?t('feature.track_time_duration.follow_wx_pub.h5_followed_title'):
        t('feature.track_time_duration.follow_wx_pub.h5_unfollowed_title')

        Taro.showModal({
            title: permission.wxPubFollow ? t('feature.track_time_duration.follow_wx_pub.modal_followed_title') :
                t('feature.track_time_duration.follow_wx_pub.modal_unfollowed_title'),
            content: permission.wxPubFollow ? t('feature.track_time_duration.follow_wx_pub.modal_followed_content') :
                t('feature.track_time_duration.follow_wx_pub.modal_unfollowed_content'),
            showCancel: true,
            cancelText: permission.wxPubFollow ? t('feature.track_time_duration.follow_wx_pub.modal_followed_cancel_btn') :
                t('feature.track_time_duration.follow_wx_pub.modal_unfollowed_cancel_btn'),
            confirmText: permission.wxPubFollow ? t('feature.track_time_duration.follow_wx_pub.modal_followed_confirm_btn') :
                t('feature.track_time_duration.follow_wx_pub.modal_unfollowed_confirm_btn'),
            success(result) {
                if (result.confirm) {
                    global.forceRefreshWXPub = true
                    jumpPage('/pages/common/H5?title=' + title + '&url=' + resource[0].url)
                }
            },
        })
    }

    function detailHeader() {
        var btnStyle;
        if (props.data.scenario == 'SLEEP') {
            btnStyle = {
                fontSize: 14,
                lineHeight: 18,
                color: global.sleepColor ? global.sleepColor : ColorType.sleep
            }
        }
        else if (props.data.scenario == 'FAST') {
            btnStyle = {
                fontSize: 14,
                lineHeight: 18,
                color: global.fastColor ? global.fastColor : ColorType.fast
            }
        }
        else if (props.data.scenario == 'FAST_SLEEP') {
            btnStyle = {
                fontSize: 14,
                lineHeight: 18,
            }
        }
        return <View style={{
            height: 18,
            overflow: 'hidden',
            display: 'flex', flexDirection: 'row', width: '100%',
            justifyContent: 'space-between', alignItems: 'center',
            marginBottom: 10, paddingRight: 10, boxSizing: 'border-box'
        }}>
            <Text style={{ fontSize: 18, lineHeight: 18, fontWeight: 'bold' }}>
                {permission.wxPubFollow ? TimeFormatter.getDateAndWeek(new Date().getTime()) :
                    t('feature.track_time_duration.schedule.unfollow_title')}</Text>
            {
                !permission.wxPubFollow && <View >
                    <Switch isOn={permission.wxPubFollow} onClick={() => followWxPub()} />
                </View>
            }
        </View>
    }

    function tapSchedule(e) {
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }

        if (permission.wxPubFollow && props.data.status == 'WAIT_FOR_START') {
            Taro.showActionSheet({
                itemList: ["调整日程"]
            })
                .then(res => {
                    switch (res.tapIndex) {
                        case 0:
                            if (props.data.name == 'FAST_SLEEP') {
                                dispatch(setStep('fast'))
                            }
                            else if (props.data.name == 'SLEEP') {
                                dispatch(setStep('sleep'))
                            }
                            else {
                                dispatch(setStep('fast'))
                            }
                            jumpPage('/pages/clock/SetSchedule')
                            break;
                        case 1:

                            break;
                    }
                })
                .catch(err => {
                    console.log(err.errMsg)
                })
        }
        else {
            Taro.vibrateShort({
                type: 'medium'
            })
        }
    }

    function detailCenter() {
        // if (!permission.wxPubFollow) {
        //     return <View className="tip_bg2">
        //         <Text className="tip_text2">{t('feature.track_time_duration.schedule.follow_tip')}</Text>
        //     </View>
        // }

        var nextCheckTimestamp = 0;
        if (time.status != 'WAIT_FOR_START') {
            if (time.status == 'ONGOING') {
                nextCheckTimestamp = time.scenario == 'FAST' ?
                    time.fast.target_end_time : time.sleep.target_end_time
            }
            else {
                switch (time.status) {
                    case 'ONGOING1':
                        nextCheckTimestamp = time.sleep.target_start_time
                        break;
                    case 'ONGOING2':
                        nextCheckTimestamp = time.sleep.target_end_time
                        break
                    case 'ONGOING3':
                        nextCheckTimestamp = time.fast.target_end_time
                        break
                }
            }

        }
        var today = new Date();
        today.setHours(0)
        today.setMinutes(0)
        today.setSeconds(0)
        if (nextCheckTimestamp != 0 && today.getTime() > nextCheckTimestamp) {
            return <View className="tip_bg2">
                <Text className="tip_text2">{t('feature.track_time_duration.schedule.timeout_tip')}</Text>
            </View >
        }

        return <View onClick={tapSchedule}>
            <TimelineStage data={props.data} isSchedule={true} title={t('feature.track_time_duration.schedule.section_title')}
                subTitle={TimeFormatter.getDateAndWeek(new Date().getTime(), true)}
            />

            {/* <TimelineFastSleep data={props.data} />
            {
                props.data.scenario == 'FAST_SLEEP' && <View className="schedule_more" onClick={showStage}>
                    <View style={{ flex: 1 }} />
                    {
                        time.scenario == 'FAST_SLEEP' ? <Text className="fast_sleep_text" style={{ textAlign: 'right' }}>{
                            props.data.status == 'WAIT_FOR_START' ?
                                t('feature.track_time_duration.schedule.duration_goals_by_stage') :
                                t('feature.track_time_duration.schedule.current_stage')
                        }</Text> :
                            <Text style={{ textAlign: 'right', color: getThemeColor(time) }}>{
                                props.data.status == 'WAIT_FOR_START' ?
                                    t('feature.track_time_duration.schedule.duration_goals_by_stage') :
                                    t('feature.track_time_duration.schedule.current_stage')
                            }</Text>
                    }
                </View>
            } */}
        </View>
    }

    function detailFooter() {

    }

    function detail() {
        return <View style={{ flexDirection: 'column', display: 'flex', alignItems: 'center', position: 'relative' }} onClick={all}>
            {/* {
                detailHeader()
            } */}
            {
                detailCenter()
            }
        </View >
    }

    function tapBox(e) {

    }

    // if (!permission.wxPubFollow) {
    //     return <View className="schedule_box">
    //         <Text className="box_title">{t('feature.track_time_duration.schedule.section_title')}</Text>
    //         <Text className="box_subtitle">{TimeFormatter.getDateAndWeek(new Date().getTime(), true)}</Text>
    //         <View className="schedule_line" />
    //         <View className="schedule_row">
    //             <Text>{t('feature.track_time_duration.schedule.follow_tip')}</Text>
    //             <Switch isOn={permission.wxPubFollow} onClick={() => followWxPub()} />
    //         </View>
    //     </View>
    // }

    var nextCheckTimestamp = 0;
    if (time.status != 'WAIT_FOR_START') {
        if (time.status == 'ONGOING') {
            nextCheckTimestamp = time.scenario == 'FAST' ?
                time.fast.target_end_time : time.sleep.target_end_time
        }
        else {
            switch (time.status) {
                case 'ONGOING1':
                    nextCheckTimestamp = time.sleep.target_start_time
                    break;
                case 'ONGOING2':
                    nextCheckTimestamp = time.sleep.target_end_time
                    break
                case 'ONGOING3':
                    nextCheckTimestamp = time.fast.target_end_time
                    break
            }
        }

    }
    var today = new Date();
    today.setHours(0)
    today.setMinutes(0)
    today.setSeconds(0)

    if (nextCheckTimestamp != 0 && today.getTime() > nextCheckTimestamp) {
        return <View className="schedule_box">
            <View className="box_header" style={{ marginRight: 20, backgroundColor: global.isDebug ? 'red' : 'transparent' }}>
                <Text className="box_title">{t('feature.track_time_duration.schedule.section_title')}</Text>
                <Switch isOn={permission.wxPubFollow} onClick={() => followWxPub()} />

            </View>

            <Text className="box_subtitle">{TimeFormatter.getDateAndWeek(new Date().getTime(), true)}</Text>
            <View className="schedule_line" />
            <View className="schedule_row">
                <Text>{t('feature.track_time_duration.schedule.timeout_tip')}</Text>
            </View>
        </View>
        return <TableCell title={t('feature.track_time_duration.schedule.timeout_tip')} showMarginBottom={true}>

        </TableCell>

    }


    return <Box>
        {
            detail()
        }
        {
            showModal && <Modal
                modalType={ModalType.center}
                confirm={() => { }}
                dismiss={() => {
                    setShowModal(false)
                }}>
                <CenterContentTitleModal title="Stage">
                    <Stage data={time} />
                </CenterContentTitleModal>
            </Modal>
        }
    </Box>


}