import { View, Text, Image, Switch } from "@tarojs/components";
import './move_schedule.scss'
import { useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import { createSchedule, getActiveMovesCurrent, getMoveSchedules } from "@/services/health";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import { rpxToPx } from "@/utils/tools";
import NewHeader, { NewHeaderType } from "../components/new_header";
import StatusIndicator, { StatusType } from "../base/status_indicator";
import { MainColorType } from "@/context/themes/color";
import { IconNotification, IconNotificationOff } from "@/components/basic/Icons";
import ConsoleCell from "../components/console_cell";

let useRoute;
let useNavigation;
let scenario = '';
if (process.env.TARO_ENV == 'rn') {
    useRoute = require("@react-navigation/native").useRoute
    useNavigation = require("@react-navigation/native").useNavigation
}
/*
https://fast-dev.oss-cn-beijing.aliyuncs.com/users/b13170f6916a27713c118a5ce75ea74a/food-journal/2024/88620d96-c898-472f-8783-d425bb91333a_20240910114628_698.png
https://fast-dev.oss-cn-beijing.aliyuncs.com/users/b13170f6916a27713c118a5ce75ea74a/food-journal/2024/88620d96-c898-472f-8783-d425bb91333a_20240910114628_698.png?x-oss-process=image/resize,w_50,limit_0
*/

let timer;
export default function MoveSchedule() {
    let router
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }

    const [hours, setHours] = useState<any>([])
    const [loaded, setLoaded] = useState(false)
    const [count, setCount] = useState(1)


    useEffect(() => {
        getData()
        timer = setInterval(() => {
            setCount((count => count + 1))
            var now = new Date()
            if (now.getMinutes() == 10 && now.getSeconds() == 0) {
                getData()
            }
        }, 1000)
        // getMoveSchedules().then(res => {
        //     console.log(hours)
        //     setLoaded(true)
        // })

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

    function getData() {
        getActiveMovesCurrent().then(res => {
            setLoaded(true)
            setHours((res as any).hours)
        })
    }

    // console.log(JSON.parse(router.params.hours))
    if (!loaded) return <View />


    function formatTimeInterval(startTimestamp, endTimestamp) {
        // 计算时间间隔（以秒为单位）
        const intervalSeconds = Math.floor((endTimestamp - startTimestamp) / 1000);

        // 处理负值的情况
        if (intervalSeconds < 0) {
            throw new Error("End timestamp must be greater than start timestamp");
        }

        // 如果时间间隔大于1小时
        if (intervalSeconds >= 3600) {
            const hours = Math.floor(intervalSeconds / 3600);
            const minutes = Math.floor((intervalSeconds % 3600) / 60);
            const seconds = intervalSeconds % 60;

            return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        } else {
            // 如果时间间隔小于1小时
            const minutes = Math.floor(intervalSeconds / 60);
            const seconds = intervalSeconds % 60;

            return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }
    }

    function firstTime(index) {
        var firstIndex = -1;
        var selHour = -1;
        for (var i = 0; i < hours.length; i++) {
            if (hours[i].status == 'WFS') {
                firstIndex = i;
                selHour = hours[i].hour
                break;
            }
        }
        if (firstIndex == index) {
            var endDate = new Date()
            endDate.setHours(selHour)
            endDate.setMinutes(10);
            endDate.setSeconds(0);
            endDate.setMilliseconds(0);
            var endTimestamp = endDate.getTime() + 3600 * 1000;
            if (new Date().getTime() > endTimestamp) {
                endTimestamp += 24 * 3600 * 1000
            }

            if (endTimestamp - new Date().getTime() > 20 * 60 * 1000) {
                return <Text>countdown {formatTimeInterval(new Date().getTime(), endTimestamp)} </Text>
            }
            else if (endTimestamp - new Date().getTime() < 10 * 60 * 1000) {
                <Text style={{ color: getThemeColor('ACTIVE') }}>Closing soon in {formatTimeInterval(new Date().getTime(), endTimestamp)} </Text>
            }
            return <Text>available </Text>
        }
        return <Text></Text>
    }

    return <View style={{ display: 'flex', flexDirection: 'column' }}>
        <NewHeader type={NewHeaderType.left} title="Upcoming Check Ins" />
        {
            hours.length == 0 && <View style={{ display: 'flex', flex: 1, flexDirection: 'column', alignItems: 'center', marginTop: rpxToPx(110) }}>
                <Image src={require('@assets/_health/sleep2.png')} style={{ width: rpxToPx(64), height: rpxToPx(64) }} />
                <Text style={{ marginTop: rpxToPx(24), fontSize: rpxToPx(50), fontWeight: 'bold', color: '#B2B2B2' }}>睡个好觉</Text>
            </View>
        }
        {
            hours.map((item, index) => {
                var start = item.hour
                var open: any = start
                var end = start + 1
                start = (start + '').padStart(2, '0')
                end = (end + '').padStart(2, '0')

                open = (open + '').padStart(2, '0')
                if (item.status != 'WFS') return <View key={index} />
                return <ConsoleCell key={index}
                    status={<StatusIndicator type={StatusType.normal}
                        color={MainColorType.active}
                        text={'WAKING HOUR ' + (index + 1)} />}
                    title={`Check in at ${open}:50`}
                    description={`${parseInt(start) < new Date().getHours() ? '' : ''}${start}:00-${end}:00`}
                    subDesc={<Text className="schedule_item_time">  {firstTime(index)}</Text>}
                    right={<View style={{
                        display: 'flex',
                        flexDirection: 'row',
                        alignItems: 'center'
                    }}>
                        {
                            item.reminder ? <IconNotification color={MainColorType.g03} width={rpxToPx(28)} /> : <IconNotificationOff color={MainColorType.g03} width={rpxToPx(28)} />
                        }
                        <View style={{ width: rpxToPx(12) }} />
                        <Switch checked={item.reminder} color={getThemeColor('ACTIVE')} onChange={e => {
                            console.log(item)

                            createSchedule({
                                schedules: [{
                                    id: item.schedule_id,
                                    reminder: e.detail.value
                                }],
                            }).then(res => {
                                getData()
                                if (global.refreshWindow) {
                                    global.refreshWindow()
                                }
                                if (global.refreshSchedules) {
                                    global.refreshSchedules()
                                }
                                if (global.updateMove) {
                                    global.updateMove()
                                }
                            })
                        }} />
                    </View>}
                    disable={true}
                    onClick={() => { }}
                    showLine={true}
                    fullLine={false}

                />

            })
        }
        <Text className="no_more" style={{ color: '#5C7099' }} onClick={() => {
            jumpPage('./move_setting_reminder')
        }}>Full schedules</Text>
    </View>
}