import { createSchedule, delSchedule, getLabelsEvent, getSchedules } from "@/services/health";
import { View, Text, Image } from "@tarojs/components";
import { useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import './schedules.scss';
import { rpxToPx } from "@/utils/tools";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import Modal from "@/components/layout/Modal.weapp";
import TimePicker from "@/features/common/TimePicker";
import showAlert from "@/components/basic/Alert";
import { IconAdd, IconError, IconNotificationOff, IconSuccess } from "@/components/basic/Icons";
import AddLabel from "../components/add_label";
import NewButton, { NewButtonType } from "../base/new_button";
import showActionSheet from "@/components/basic/ActionSheet";
import Card from "../components/card";
import StatusIndicator, { StatusType } from "../base/status_indicator";
import { MainColorType } from "@/context/themes/color";
import { AtSwipeAction } from "taro-ui"
import ScheduleItem from "../components/schedule_item";
import { useTranslation } from "react-i18next";
import NewHeader, { NewHeaderType } from "../components/new_header";
import ListFooter from "../components/list_footer";

let useRoute;
let useNavigation;
let scenario = '';
if (process.env.TARO_ENV == 'rn') {
    useRoute = require("@react-navigation/native").useRoute
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function Schedules() {
    let navigation, showActionSheetWithOptions;

    let router
    if (useNavigation) {
        navigation = useNavigation()
    }

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }
    const [list, setList] = useState<any>([])
    const [labels, setLabels] = useState<any>([])
    const [labels2, setLabels2] = useState<any>([])
    const [showAutoSave, setShowAutoSave] = useState(false)
    const [errors, setErrors] = useState<any>(router.params.errors ? JSON.parse(router.params.errors) : [])
    const [showTimePicker, setShowTimePicker] = useState(false)
    const health = useSelector((state: any) => state.health);
    const [selItem, setSelItem] = useState<any>(null)
    const [selIndex, setSelIndex] = useState(-1)
    const [showModal, setShowModal] = useState(false)
    const [highlight, setHighlight] = useState(true)
    const [tempArray, setTempArray] = useState<any>([])
    const [btnEnable, setBtnEnable] = useState(true)
    const [selMode, setSleMode] = useState(router.params.mode);
    const [isEat, setIsEat] = useState(false)
    const [loaded, setLoaded] = useState(false)
    const { t } = useTranslation()

    useEffect(() => {
        if (selMode == '' && router.params.schedules) {
            setList(JSON.parse(router.params.schedules))
            if (router.params.errors) {
                setErrors(JSON.parse(router.params.errors))
            }
        }
        else {
            schedules()
            if (selMode != '') {
                global.refreshSchedules2 = () => {
                    schedules()
                }
            }

        }

    }, [])



    global.tempRefresh = () => {
        schedules()
    }

    function schedules() {
        let windows = ''
        switch (selMode) {
            case 'FAST':
                if (router.params.isFastSleep){
                    windows = 'FAST,SLEEP';
                }
                else {
                    windows = 'FAST,EAT';
                }
                
                break
            case 'EAT':
                windows = 'EAT,FAST';
                break
            case 'SLEEP':
                windows = 'SLEEP,ACTIVE';
                break
            case 'ACTIVE':
                windows = 'ACTIVE,SLEEP';
                break
            case 'DAY':
                windows = 'DAY,NIGHT';
                break
            case 'NIGHT':
                windows = 'NIGHT,DAY';
                break
        }
        getSchedules({ window: windows }).then(res => {
            setList((res as any).data)
            setErrors([])
            setLoaded(true)
            setTimeout(() => {
                setHighlight(false)
            }, 2000)
        }).catch(e => {

        })

        getLabelsEvent({ window: 'EAT' }).then(res => {
            setLabels((res as any).labels)
        })
        getLabelsEvent({ window: 'ACTIVE' }).then(res => {
            setLabels2((res as any).labels)
        })
    }

    function getTitle() {
        switch (selMode) {
            case 'FAST':
                if (router.params.isFastSleep){
                    return '断食和睡眠';
                }
                return '断食和进食';
            case 'EAT':
                return '进食和断食';
            case 'SLEEP':
                return '睡眠和活动';
            case 'ACTIVE':
                return '活动和睡眠';
            case 'DAY':
                return '白天和夜晚';
            case 'NIGHT':
                return '夜晚和白天';
        }
        return '全部'
    }

    function modalContent() {
        const strTime = selItem.time

        var title = selItem.title
        var color = getThemeColor(selItem.window)

        return <TimePicker time={strTime}
            color={color}
            title={title}
            confirm={(e) => {
                selItem.time = e
                setSelItem(selItem)
                setShowTimePicker(false)
                var array = JSON.parse(JSON.stringify(list))
                array[selIndex].time = e
                array[selIndex].op_ms = new Date().getTime()
                setList(array)
                checkData(array)
                // confirmPickerTime(e)
            }}
            cancel={() => {
                setShowTimePicker(false)
            }} />
    }

    function checkData(array) {
        setTempArray(array)
        createSchedule({
            schedules: array,
            // only_check: true
        }).then(res => {
            checkResultData(res)


        })
    }

    function checkResultData(res) {
        if ((res as any).result) {
            setShowAutoSave(true)
            setErrors([])
            setList((res as any).schedules)
            global.refreshWindow()
            if (global.refreshSchedules) {
                global.refreshSchedules()
            }
            if (global.refreshSchedules2) {
                global.refreshSchedules2()
            }
        }
        else {
            setShowAutoSave(false)
            setList((res as any).schedules)
            setErrors((res as any).error_messages ? (res as any).error_messages : [])
            var array = (res as any).conflict_windows;
            var showMore = false;
            if (array.length > 2) {
                showMore = true;
            }
            else if (array.length == 1) {
                showMore = false;
            }
            else {
                // 判断是否同时存在 FAST 和 EAT
                const containsFastAndEat = array.includes('FAST') && array.includes('EAT');

                // 判断是否同时存在 SLEEP 和 ACTIVE
                const containsSleepAndActive = array.includes('SLEEP') && array.includes('ACTIVE');

                // 最终结果
                const result = containsFastAndEat || containsSleepAndActive;
                showMore = !result;
            }
            if (selMode != '' && showMore) {
                showAlert({
                    title: t('health.schedule_conflict'),
                    content: t('health.conflict_desc'),
                    showCancel: false,
                    confirmText: t('health.check_conflict'),
                    confirm: () => {
                        setSleMode('')
                        // jumpPage(`./schedules?mode=&schedules=${JSON.stringify((res as any).schedules)}&errors=${JSON.stringify((res as any).error_messages)}`)
                    }
                })
            }
            else {
                // setList((res as any).schedules)
                // setErrors((res as any).error_messages ? (res as any).error_messages : [])
            }
        }
    }

    function add(isEat) {
        var isMax = false
        if (isEat) {
            setIsEat(true)
            const countFastWindows = list.filter(item => item.window === 'EAT').length;
            if (countFastWindows >= 4) {
                isMax = true
            }
        }
        else {
            setIsEat(false)
            const countFastWindows = list.filter(item => item.window === 'ACTIVE').length;
            if (countFastWindows >= 4) {
                isMax = true
            }
        }
        if (isMax) {
            showAlert({
                title: '会员',
                content: '会员desc',
                showCancel: true,
                confirm: () => {
                    jumpPage('/pages/store/product_list', 'ProductList', navigation)
                }
            })
            return;
        }
        setShowModal(true)
    }

    function getAddColor() {
        if (selMode == 'FAST' || selMode == 'EAT') {
            return getThemeColor('EAT')
        }
        return getThemeColor('ACTIVE')
    }

    function tapEdit() {

    }

    function itemStyle(obj) {
        if (obj.is_conflict) {
            return {
                // backgroundColor: '#FF00001A',
                // color: '#FF0000'
                backgroundColor: '#B2B2B21A',
                color: '#000',
                borderWidth: 2,
                borderColor: '#FF0000',
                borderStyle: 'solid'
            }
        }
        if (errors.length > 0) {
            return {
                backgroundColor: '#B2B2B21A',
                color: '#000'
            }
        }
        return {
            backgroundColor: obj.window == selMode ? getThemeColor(selMode) + '1A' : '#B2B2B21A',
            color: obj.window == selMode ? getThemeColor(selMode) : '#000'
        }
    }

    function showAll() {
        if (!btnEnable) {
            return
        }
        if (errors.length == 0) {
            jumpPage('/_health/pages/schedules?mode=')
        }
        else {
            setBtnEnable(false)
            createSchedule({
                schedules: tempArray,
                return_all: true
                // only_check: true
            }).then(res => {
                setBtnEnable(true)
                jumpPage('/_health/pages/schedules?mode=&schedules=' + JSON.stringify((res as any).schedules) + '&errors=' + JSON.stringify((res as any).error_messages))
            })
        }

    }

    function more() {
        var items: any = ['设置提醒', '个性化名称'];
        if (errors.length == 0) {
            items.push(t('health.reset_schedule'))
        }
        showActionSheet({
            showActionSheetWithOptions: showActionSheetWithOptions,
            title: 'Oprate Title',
            itemList: items,
            success: (res) => {
                if (res == 0 || res == 1) {
                    var url = `./schedules_edit?type=${res == 0 ? 'reminder' : 'name'}&mode=${selMode}`
                    console.log(url)
                    jumpPage(url)
                }
                else if (res == 2) {
                    jumpPage('/_health/pages/guide_begin')
                }

            }
        });
    }

    function getOpPage() {

        if (selMode == '') return 'SCHEDULE_ALL'
        switch (selMode) {
            case 'FAST':
                return 'SCHEDULE_FAST_EAT';
            case 'EAT':
                return 'SCHEDULE_EAT_FAST';
            case 'SLEEP':
                return 'SCHEDULE_SLEEP_ACTIVE';
            case 'ACTIVE':
                return 'SCHEDULE_ACTIVE_SLEEP';
        }
    }

    if (!loaded) return <View />


    return <View>
        <View style={{ display: 'flex', flexDirection: 'column' }}>
            <NewHeader type={NewHeaderType.left} title={getTitle()} />

            <Card>
                <View>
                    {
                        errors.map((item, index) => {
                            return <View key={index} className='error_tip'>
                                <StatusIndicator type={StatusType.img}
                                    fontColor="#000"
                                    fontSize={rpxToPx(24)}
                                    text={item} color={MainColorType.error}>
                                    <IconError color="#fff" width={rpxToPx(26)} />
                                </StatusIndicator>
                            </View>
                            // return <View key={index} className='error_tip'>{item}</View>
                        })
                    }
                    {
                        showAutoSave && <View className='success_tip'>
                            <StatusIndicator type={StatusType.img}
                                fontColor="#000"
                                fontSize={rpxToPx(24)}
                                text='已自动保存' color={MainColorType.success}>
                                <IconSuccess color="#fff" width={rpxToPx(26)} />
                            </StatusIndicator>
                        </View>
                    }
                    {
                        !health.finish_setup && selMode == '' && <View className='success_tip' style={{ backgroundColor: MainColorType.blue + '1A', color: MainColorType.blue }}>You haven't finished setting up your schedule yet!</View>
                    }
                    {
                        list.map((obj, i) => {
                            return <ScheduleItem
                                index={i}
                                count={list.length}
                                key={i * 100}
                                obj={obj}
                                highlight={false}
                                showLine={i < list.length - 1}
                                errors={errors}
                                selMode={selMode}
                                disable={!health.finish_setup}
                                onChange={time => {
                                    obj.time = time
                                    setSelItem(obj)
                                    setShowTimePicker(false)
                                    var array = JSON.parse(JSON.stringify(list))
                                    array[i].time = time
                                    array[i].op_ms = new Date().getTime()
                                    setList(array)
                                    checkData(array)
                                }}
                                onDelete={() => {
                                    delSchedule(obj.id).then(res => {
                                        var array = JSON.parse(JSON.stringify(list))
                                        array.splice(i, 1)
                                        setList(array)

                                        global.refreshWindow()
                                    })
                                }}
                            />
                        })
                    }
                </View>
            </Card>
            <View style={{ height: 20, flexShrink: 0 }} />
            {
                !router.params.isFastSleep && selMode != '' && selMode != 'DAY' && selMode != 'NIGHT' && <Card><View className='item_add'
                    onClick={() => add((selMode == 'FAST' || selMode == 'EAT'))}>
                    <StatusIndicator type={StatusType.img}
                        fontColor={getAddColor()}
                        fontSize={rpxToPx(34)}
                        text={(selMode == 'FAST' || selMode == 'EAT') ? t('health.add_meal') : t('health.add_active')} color={getAddColor()}>
                        <IconAdd color="#fff" width={rpxToPx(20)} />
                    </StatusIndicator>
                    {/* <IconAdd color={getAddColor()} width={rpxToPx(34)} />
                    <View className='toolbar_btn' style={{ color: getAddColor() }} >添加</View> */}
                    <View style={{ flex: 1 }} />
                </View></Card>
            }
            {
                selMode == '' && <Card>
                    <View className='item_add'
                        style={{ position: 'relative' }}
                        onClick={() => add(true)}>
                        <StatusIndicator type={StatusType.img}
                            fontColor={MainColorType.eat}
                            fontSize={rpxToPx(34)}
                            text={t('health.add_meal')} color={MainColorType.eat}>
                            <IconAdd color="#fff" width={rpxToPx(20)} />
                        </StatusIndicator>
                        <View style={{ flex: 1 }} />
                        <View className='border_footer_line' style={{ left: rpxToPx(66) }} />
                    </View>
                    <View className='item_add'
                        onClick={() => add(false)}>
                        <StatusIndicator type={StatusType.img}
                            fontColor={MainColorType.active}
                            fontSize={rpxToPx(34)}
                            text={t('health.add_active')} color={MainColorType.active}>
                            <IconAdd color="#fff" width={rpxToPx(20)} />
                        </StatusIndicator>
                        <View style={{ flex: 1 }} />
                    </View>
                </Card>
            }

            {
                health.finish_setup && <View style={{
                    backgroundColor: 'transparent',
                    position: 'relative',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: rpxToPx(128),
                    width: rpxToPx(750)
                }}>
                    {
                        selMode != '' && <View style={{ width: rpxToPx(316), height: rpxToPx(128), display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            <NewButton
                                type={NewButtonType.link}
                                title='View Full Schedule'
                                onClick={showAll}
                            >
                            </NewButton>
                        </View>}
                    <NewButton
                        btnStyle={{
                            position: 'absolute',
                            top: rpxToPx(42),
                            right: rpxToPx(40)
                        }}
                        type={NewButtonType.more}
                        onClick={more}
                    />

                </View>
            }


            {/* <View style={{ height: 100, flexShrink: 0 }} /> */}
            <ListFooter />

            <View style={{ flex: 1 }} />
            {
                selMode == '' && !health.finish_setup && <View className="main_footer">
                    <NewButton
                        type={NewButtonType.fill}
                        title={t('health.finish_setup')}
                        disable={errors.length > 0}
                        color={MainColorType.blue}
                        width={rpxToPx(646)}
                        height={rpxToPx(96)}
                        onClick={() => {
                            jumpPage('/_health/pages/guide_begin')
                        }}
                    />
                </View>
            }


            {/* <View className="edit_footer_btn" style={{ color: getThemeColor(health.mode), backgroundColor: getThemeColor(health.mode) + '33' }} onClick={tapEdit}>批量编辑</View> */}
            {
                showTimePicker && <Modal
                    testInfo={null}
                    dismiss={() => {
                        setShowTimePicker(false)
                    }}
                    confirm={() => { }}>
                    {
                        modalContent()
                    }
                </Modal>
            }
            {
                showModal && <AddLabel labels={isEat ? labels : labels2}
                    window={isEat ? 'EAT' : 'ACTIVE'}
                    color={isEat ? MainColorType.eat : MainColorType.active}
                    disMiss={() => setShowModal(false)}
                    op_page={getOpPage()}
                    confirm={(res) => {
                        checkResultData(res)
                    }}
                />
            }
        </View>
    </View>
}