import { View, ScrollView, Swiper, SwiperItem } from "@tarojs/components";
import './Clock.scss'
import { useEffect, useRef, useState } from "react";
import MainDayNightCard from "@/features/health/MainDayNightCard";
import MainFastEatCard from "@/features/health/MainFastEatCard";
import MainSleepActiveCard from "@/features/health/MainSleepActiveCard";
import TabBar from "@/components/navigation/TabBar";
import { 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 { getArchived, windows } from "@/services/health";
import { useDispatch, useSelector } from "react-redux";
import health, { setEatArchived, setFastWithSleep, setLongFast, setRefreshs, setTitle, setWindows } from "@/store/health";
import dayjs from "dayjs";
import Modal from "@/components/layout/Modal.weapp";
import Streak from "@/features/health/Streak";
import Calendar from "@/features/health/calendar";
import { MainColorType } from "@/context/themes/color";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { getThemeColor } from "@/features/health/hooks/health_hooks";

export default function ClockNew() {
    const [count, setCount] = useState(0)
    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 [showCalendar, setShowCalendar] = useState(false)
    const [isPulling,setIsPulling] = useState(false)
    const healthRef = useRef(health)
    const dispatch = useDispatch();
    global.dispatch = dispatch;

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

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

    useEffect(() => {
        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()
                    // archived();
                    getArchived('EAT').then(res => {
                        dispatch(setEatArchived((res as any).latest))
                    })

                    global.refreshHistory()
                }
            })
        }, 1000)


    }, [])

    useEffect(() => {
        getWindows();
    }, [user.isLogin])

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

    function getWindows() {
        windows().then(res => {
            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))

            setIsPulling(false)
        })
        archived()
    }

    function archived() {
        if (health.mode == 'EAT' || health.mode == 'ACTIVE') {
            getArchived(health.mode).then(res => {
                if (health.mode == 'EAT') {
                    dispatch(setEatArchived((res as any).latest))
                }
            })
        }
    }

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

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

    function pageChanged(index) {

    }

    function typeChanged(str) {

    }

    function detail() {

        if (!health.windows) {
            return <View />
        }
        return <ScrollView style='height:100vh' 
        refresherEnabled
        refresherBackground={MainColorType.g05}
        onRefresherRefresh={()=>{
            global.refreshWindow()
            setIsPulling(true)
        }}
        refresherTriggered={isPulling}
        scrollY onScroll={e => {
            if (e.detail.scrollTop > 240) {
                dispatch(setTitle(health.mode))
            }
            else {
                dispatch(setTitle(''))
            }
        }}>
            <MainSwiper count={count} pageChanged={pageChanged} typeChanged={typeChanged} />
            <MainConsole type={type} />

            <MainHistory />
            <View style={{ height: 200 }} />
        </ScrollView>
    }
    //https://blog.csdn.net/weixin_43525284/article/details/130182218
    return <View style={{ flex: 1 }}>
        {
            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()
                }
            </ScrollView>
        }
        {/* <View className="tabs">
            <View className="item" onClick={() => tapScroll(0)}> tab 0</View>
            <View className="item" onClick={() => tapScroll(1)}>tab 1</View>
            <View className="item" onClick={() => tapScroll(2)}>tab 2</View>
        </View>
        <ScrollView scrollX
            scrollLeft={scrollLeft}
            scrollWithAnimation={true}
            pagingEnabled={true}
            enableFlex
            onScroll={scroll}
            style={{ width: rpxToPx(750), display: 'flex', flexDirection: 'row', overflow: 'hidden' }}
            enhanced>
            <View style={{ display: 'flex', flexShrink: 0, width: rpxToPx(750) }}>
                <MainDayNightCard count={count} />
            </View>
            <View style={{ display: 'flex', flexShrink: 0, width: rpxToPx(750) }}>
                <MainFastEatCard count={count} />
            </View>

            <View style={{ display: 'flex', flexShrink: 0, width: rpxToPx(750) }}>
                <MainSleepActiveCard count={count} />
            </View>




        </ScrollView> */}

        <TabBar index={0} />
    </View>
}