import { View, ScrollView, Swiper, SwiperItem, Image } from "@tarojs/components";
import './Clock.scss'
import { useEffect, useRef, useState } from "react";
import TabBar from "@/components/navigation/TabBar";
import { compareVersion, getTimezone, rpxToPx } from "@/utils/tools";
import MainSwiper from "@/features/health/MainSwiper";
import MainConsole from "@/features/health/MainConsole";
import MainHistory from "@/features/health/MainHistory";
import { WindowType } from "@/utils/types";
import { getLatestJournal, windows } from "@/services/health";
import { useDispatch, useSelector } from "react-redux";
import health, { setActiveArchived, setActiveArchivedTotal, setActiveTip, setEatArchived, setEatArchivedTotal, setEatTip, setFastWithSleep, setFinishSetup, setLongFast, setRefreshs, setTitle, setWindows } from "@/store/health";
import dayjs from "dayjs";
import { MainColorType } from "@/context/themes/color";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import StatusIndicator, { StatusType } from "@/_health/base/status_indicator";
import { useTranslation } from "react-i18next";
import StickyDateList from "@/_health/components/sticky_date_list";
import NoData from "@/_health/components/no_data";
import Taro, { useDidShow } from "@tarojs/taro";
import { IconClose } from "@/components/basic/Icons";
import showAlert from "@/components/basic/Alert";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";

let AppState;
if (process.env.TARO_ENV == 'rn') {
    AppState = require("react-native").AppState
}

export default function ClockNew(props: { children: any, onScroll: any }) {
    const [count, setCount] = useState(0)
    const [loaded, setLoaded] = useState(false)
    const [showRetry, setShowRetry] = useState(false)
    const [scrollLeft, setScrollLeft] = useState(rpxToPx(750) * 0)
    const user = useSelector((state: any) => state.user);
    const health = useSelector((state: any) => state.health);
    const [type, setType] = useState(WindowType.day)
    const [needShowAddTip, setNeedShowAddTip] = useState(false)
    const [reminderAdd, setReminderAdd] = useState(true)
    const [showDate, setShowDate] = useState(false)
    const [date, setDate] = useState('')
    const [isPulling, setIsPulling] = useState(false)
    const healthRef = useRef(health)
    const historyRef2 = useRef()
    const dispatch = useDispatch();
    const { t } = useTranslation()
    global.dispatch = dispatch;

    const handleAppStateChange = (nextAppState) => {
        if (nextAppState != 'active') {
            return
        }
        if (nextAppState == 'active') {
            checkTimeZone()
            refreshData()
        }

    };

    useDidShow(() => {
        if (process.env.TARO_ENV == 'weapp') {
            checkTimeZone()
        }

        setTimeout(() => {
            checkVersionUpdate();
        }, 1000)
    })

    function refreshData() {
        global.refreshWindow()
        global.refreshHistory()
    }

    function checkTimeZone() {
        if (!user.isLogin) return
        var timeZoneFormatted = getTimezone()
        Taro.getStorage({
            key: 'last_tz',
            success: function (res) {
                if (res.data && res.data != timeZoneFormatted) {
                    showAlert({
                        title: t('feature.track_time_duration.change_tz_alert.title'),
                        content: t('feature.track_time_duration.change_tz_alert.content', { tz: timeZoneFormatted }),
                        showCancel: false,
                        confirmText: t('feature.track_time_duration.change_tz_alert.confirm'),
                    })
                    // }
                }
            },
            complete: function () {
                Taro.setStorage({ key: 'last_tz', data: timeZoneFormatted })
            }
        })
    }


    useEffect(() => {
        healthRef.current = health;
    }, [health])

    // useEffect(() => {
    //     archived()
    // }, [health.mode])

    useEffect(() => {
        if (process.env.TARO_ENV == 'rn') {
            AppState.addEventListener('change', handleAppStateChange);
        }
        Taro.onAppShow(() => {
            refreshData()
        })
        setInterval(() => {
            setCount(index => index + 1)
            healthRef.current.refreshs.map((item) => {
                const strTime = dayjs(item).format('YYYY-MM-DDTHH:mm:ss')
                const now = dayjs().format('YYYY-MM-DDTHH:mm:ss')
                if (strTime == now) {
                    getWindows()

                    if (global.refreshHistory) {
                        global.refreshHistory()
                    }


                }
            })
        }, 1000)

        setTimeout(() => {
            checkVersionUpdate();
        }, 1500)


    }, [])

    useEffect(() => {
        getWindows();
        if (global.refreshHistory) {
            global.refreshHistory()
        }

    }, [user.isLogin])

    global.refreshWindow = () => {
        getWindows();

    }

    function getWindows() {
        checkAddToMini()
        windows().then(res => {
            setLoaded(true)
            setShowRetry(false)
            if (!(res as any).windows.night_day.night.target) {
                var date = new Date()
                var hour = date.getHours()
                if (hour >= 6 && hour < 18) {
                    var date1 = new Date()
                    date1.setHours(6)
                    date1.setMinutes(0)
                    date1.setSeconds(0)

                    var date2 = new Date()
                    date2.setHours(18)
                    date2.setMinutes(0)
                    date2.setSeconds(0);

                    (res as any).windows.night_day.day.target = {
                        start_timestamp: date1.getTime(),
                        end_timestamp: date2.getTime(),
                        duration: 12 * 60 * 60 * 1000
                    };

                    (res as any).windows.night_day.night.target = {
                        start_timestamp: date2.getTime(),
                        end_timestamp: date2.getTime() + 12 * 60 * 60 * 1000,
                        duration: 12 * 60 * 60 * 1000
                    }
                }
                else {
                    var date1 = new Date()
                    date1.setHours(18)
                    date1.setMinutes(0)
                    date1.setSeconds(0);

                    (res as any).windows.night_day.day.target = {
                        start_timestamp: date1.getTime(),
                        end_timestamp: date1.getTime() + 12 * 60 * 60 * 1000,
                        duration: 12 * 60 * 60 * 1000
                    };

                    (res as any).windows.night_day.night.target = {
                        start_timestamp: date1.getTime() + 12 * 60 * 60 * 1000,
                        end_timestamp: date1.getTime() + 12 * 60 * 60 * 1000 + 12 * 60 * 60 * 1000,
                        duration: 12 * 60 * 60 * 1000
                    }
                }
            }
            dispatch(setFastWithSleep((res as any).fast_with_sleep))
            dispatch(setWindows((res as any).windows))
            dispatch(setLongFast((res as any).long_fast))
            dispatch(setRefreshs((res as any).refresh_timestamps))
            dispatch(setFinishSetup((res as any).finish_setup))
            setIsPulling(false)
        }).catch(e => {
            setShowRetry(true)
        })
        archived()
    }

    function archived() {
        return
        getLatestJournal(true, {
            window: 'EAT',
        }).then(res => {
            if (!(res as any).user_confirmed && (res as any).id) {
                global.eatTipId = (res as any).id
                dispatch(setEatTip(true))
            }
        })
        getLatestJournal(true, {
            window: 'ACTIVE'
        }).then(res => {
            if (!(res as any).user_confirmed && (res as any).id) {
                global.activeTipId = (res as any).id
                dispatch(setActiveTip(true))
            }
        })

        // if (health.mode == 'EAT' || health.mode == 'ACTIVE') {
        //     getLatestJournal(true, health.mode).then(res => {
        //         if (!(res as any).user_confirmed && (res as any).id) {
        //             if (health.mode == 'EAT') {
        //                 // dispatch(setEatArchived((res as any).latest))
        //                 // dispatch(setEatArchivedTotal((res as any).archived_total))
        //                 dispatch(setEatTip(true))
        //             }
        //             else if (health.mode == 'ACTIVE') {
        //                 dispatch(setActiveTip(true))
        //                 // dispatch(setActiveArchived((res as any).latest))
        //                 // dispatch(setActiveArchivedTotal((res as any).archived_total))
        //             }
        //         }
        //     })
        //     // getArchived(health.mode).then(res => {
        //     //     if (health.mode == 'EAT') {
        //     //         dispatch(setEatArchived((res as any).latest))
        //     //         dispatch(setEatArchivedTotal((res as any).archived_total))
        //     //     }
        //     //     else if (health.mode == 'ACTIVE') {
        //     //         dispatch(setActiveArchived((res as any).latest))
        //     //         dispatch(setActiveArchivedTotal((res as any).archived_total))
        //     //     }
        //     // })
        // }
    }

    function checkAddToMini() {
        if (process.env.TARO_ENV == 'weapp' && user.isLogin && reminderAdd) {
            const version = Taro.getAppBaseInfo().SDKVersion
            if (compareVersion(version, '2.30.3') >= 0) {
                wx.checkIsAddedToMyMiniProgram({
                    success: (res) => {
                        if (!res.added) {
                            setNeedShowAddTip(true)
                        }
                    },
                    fail: (e) => {
                    }
                });
            }
        }

    }

    async function checkVersionUpdate() {
        if (!user.isLogin) {
            return
        }


        const showAlert1 = await getStorage('148alert') || false;
        Taro.setStorage({ key: '148alert', data: true })
        console.log('test abc')
        if (!showAlert1 && !health.finish_setup){
            jumpPage('/_health/pages/guide_begin')
        }

    }

    async function getStorage(key: string) {
        try {
            const res = await Taro.getStorage({ key });
            return res.data;
        } catch {
            return '';
        }
    }

    function tapScroll(index) {
        setScrollLeft(rpxToPx(750) * index)
    }

    function scroll(e) {
        console.log(e.detail.scrollLeft)
    }

    function pageChanged(index) {

    }

    function typeChanged(str) {

    }

    function pageTitle() {
        switch (health.mode) {
            case 'DAY':
                return t('health.window_day')
            case 'NIGHT':
                return t('health.night')
            case 'FAST':
                return t('health.fast')
            case 'EAT':
                return t('health.eat')
            case 'SLEEP':
                return t('health.sleep')
            case 'ACTIVE':
                return t('health.active')
        }
    }

    function detail() {
        // return <View>11111</View>
        if (!health.windows) {
            return <View />
        }
        return <StickyDateList
            isPulling={isPulling}
            showDate={showDate}
            date={date}
            disable={props.children}
            onRefresherRefresh={() => {
                global.refreshWindow()
                setIsPulling(true)
                if (global.refreshHistory) {
                    global.refreshHistory()
                }
            }}
            loadMore={() => {
                if (historyRef2) {
                    (historyRef2.current as any).more()
                }
            }}
            onScroll={e => {
                props.onScroll(e)
                if (e.detail.scrollTop > 240) {
                    dispatch(setTitle(pageTitle()))
                }
                else {
                    dispatch(setTitle(''))
                }
                if (historyRef2) {
                    (historyRef2.current as any).onScroll(e)
                }
            }}
        >
            <View style={{ display: 'flex', flexDirection: 'column' }}>
                {
                    needShowAddTip && reminderAdd && <View className="guide_tip h26">{t('health.add_mini_guide_tip')}
                        <NewButton type={NewButtonType.img} btnStyle={{
                            position: 'absolute',
                            right: 0,
                            top: 0,
                            bottom: 0,
                            width: rpxToPx(92)
                        }} onClick={() => {
                            setReminderAdd(false)
                            console.log('ssssss')
                        }}>
                            <IconClose color={MainColorType.g01} width={rpxToPx(32)} height={rpxToPx(32)} />
                        </NewButton>

                    </View>
                }
                <MainSwiper count={count} pageChanged={pageChanged} typeChanged={typeChanged} />
                <MainConsole type={type} />

                <MainHistory ref={historyRef2} updateDate={(e) => {
                    setShowDate(e.show)
                    setDate(e.date)
                }} />
                <View style={{ height: user.isLogin ? 150 : 300 }} />
                {
                    (health.mode == 'DAY' || health.mode == 'NIGHT') && <View style={{ height: 150, flexShrink: 0 }} />
                }
                {
                    props.children
                }
            </View>
        </StickyDateList>
    }
    //https://blog.csdn.net/weixin_43525284/article/details/130182218

    if (!loaded && showRetry) return <NoData refresh={
        () => {
            getWindows();
            if (global.refreshHistory) {
                global.refreshHistory()
            }
        }
    } />
    return <View style={{ flex: 1, position: 'relative' }}>
        {
            process.env.TARO_ENV == 'weapp' ? detail() : <ScrollView style={{ flex: 1, backgroundColor: MainColorType.bg }} onScroll={e => {
                if (e.detail.scrollTop > 240) {
                    dispatch(setTitle(health.mode))
                }
                else {
                    dispatch(setTitle(''))
                }
            }}>
                {
                    detail()
                }
                {
                    props.children()
                }

            </ScrollView>
        }

        {
            process.env.TARO_ENV == 'weapp' && <TabBar index={0} />
        }


    </View>
}