import { View, Text } from "@tarojs/components";
import './Clock.scss'
import ClockNew from "./ClockNew";
import { useEffect, useState } from "react";
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { useDispatch, useSelector } from "react-redux";
import { getInfoSuccess } from "@/store/user";
import { useTranslation } from "react-i18next";
import { MainColorType } from "@/context/themes/color";
import { IconMap, IconStreak } from "@/components/basic/Icons";
import { getScenario, getThemeColor } from "@/features/health/hooks/health_hooks";
import Streak from "@/features/health/Streak";
import Calendar from "@/features/health/calendar";
import HeaderCircadian from "@/features/health/HeaderCircadian";
import { rpxToPx } from "@/utils/tools";
import AddLabel from "@/_health/components/add_label";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import showAlert from "@/components/basic/Alert";
import { setTitle } from "@/store/health";
import { globalSetting } from "@/services/common";

let useNavigation;

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

let scrollTop = 0
export default function Clock() {
    const dispatch = useDispatch();
    const [loaded, setLoaded] = useState(false)

    const { t } = useTranslation()
    const health = useSelector((state: any) => state.health);
    const user = useSelector((state: any) => state.user);
    const [showCalendar, setShowCalendar] = useState(false)
    const [showStreak, setShowStreak] = useState(true)

    const systemInfo: any = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync();
    const navigationBarHeight = systemInfo.statusBarHeight + 44;
    const [showModal, setShowModal] = useState(false)
    const [labels, setLabels] = useState<any>([])

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


    if (process.env.TARO_ENV == 'weapp') {
        useShareAppMessage((e) => {
            return {
                title: t('feature.track_time_duration.common.share_title'),
                path: 'pages/clock/Clock'
            }
        })
    }

    global.showIndexAddActive = (array) => {
        setLabels(array)
        setShowModal(true)
    }

    useEffect(() => {
        if (navigation) {
            navigation.setOptions({
                headerTitle: '',
            });
        }

        dispatch(setTitle(''))
        global.memberAlert = false;
        if (process.env.TARO_ENV == 'weapp') {
            loadWXCache()
        }
        else {
            loadRNCache()
        }
        getSetting()
    }, [])

    function getSetting() {
        globalSetting({
            keys: 'mp_status'
        }).then(res => {
            if ((res as any).data && (res as any).data.length > 0 && (res as any).data[0].value.status == 'PENDING') {
                global.allowShare = false
            }
            else {
                global.allowShare = true
            }
        })
    }

    function loadWXCache() {
        var gps = Taro.getStorageSync('gps')
        if (gps) {
            global.locationDetail = JSON.parse(gps)
        }
        global.memberAlert = Taro.getStorageSync('memberAlert') || false
        var userData = Taro.getStorageSync('userData')
        if (userData) {
            console.log('load user cache')
            dispatch(getInfoSuccess(JSON.parse(userData)));
        }
        setLoaded(true)
    }

    async function loadRNCache() {
        var showDayRing = await getStorage('showDayRing') || false;
        var showNightRing = await getStorage('showNightRing') || false;
        global.memberAlert = await getStorage('memberAlert') || false
        var gps = await getStorage('gps')
        if (gps) {
            global.locationDetail = JSON.parse(gps)
        }
        var userData = await getStorage('userData')
        console.log(userData)
        if (userData) {
            dispatch(getInfoSuccess(JSON.parse(userData)));
        }
        setLoaded(true)
    }

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

    function getStreakCount() {
        const scenario = getScenario(health.windows, health.mode)
        return scenario.current_streak && scenario.current_streak.days
    }

    function getStreakDesc() {
        switch (health.mode) {
            case 'FAST':
                return t('health.faststreak')
            case 'EAT':
                return t('health.eatstreak')
            case 'SLEEP':
                return t('health.sleepstreak')
            case 'ACTIVE':
                return t('health.activestreak')
        }
        return ''
    }

    function haveStreaks() {


        if (user.isLogin && health.windows && health.mode.length > 0) {
            const scenario = getScenario(health.windows, health.mode)
            if (scenario.current_streak) {
                return true
            }
        }
        return false
    }

    function steakIcon() {
        if (!haveStreaks()) return <View />
        if (showCalendar) {
            return <View className="navi-streak"
                onClick={() => {
                    setShowCalendar(false)
                }}
                style={{ height: 44, marginTop: systemInfo.statusBarHeight, }}>
                <View style={{
                    zIndex: 1,
                    height: rpxToPx(64),
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    backgroundColor: getThemeColor(health.mode),
                    borderRadius: rpxToPx(64),
                    paddingRight: rpxToPx(24)
                }} onClick={() => {
                    setShowCalendar(false)
                }}>
                    <View style={{ width: rpxToPx(16) }} />
                    <IconStreak color='#fff' width={20} full="#fff" />
                    <View style={{ width: rpxToPx(4) }} />
                    <Text className="h30 bold" style={{ color: '#fff' }}>{getStreakDesc()}</Text>
                </View>

            </View>
        }
        else {
            return <View className="navi-streak"
                onClick={() => {
                    setShowCalendar(true)
                }}
                style={{ height: 44, marginTop: systemInfo.statusBarHeight, }}>
                <View style={{ width: rpxToPx(16) }} />
                <IconStreak color='#000' width={20} full="transparent" />
                <View style={{ width: rpxToPx(4) }} />
                <Text className="h34 bold" style={{ color: '#000' }}>{getStreakCount()}</Text>
            </View>
        }
    }

    function getCity() {
        var city = ''
        var scenario = getScenario(health.windows, health.mode)
        if (scenario.extra.address) {
            if (scenario.extra.address.city.length > 0) {
                city = scenario.extra.address.city
            }
            else if (scenario.extra.address.province.length > 0) {
                city = scenario.extra.address.province
            }
            else if (scenario.extra.address.country.length > 0) {
                city = scenario.extra.address.country
            }
            else {
                city = `${Math.abs(parseInt(scenario.extra.lat))}°${parseInt(scenario.extra.lat) < 0 ? 'S' : 'N'} ${Math.abs(parseInt(scenario.extra.lng))}°${parseInt(scenario.extra.lng) < 0 ? 'W' : 'E'}`
                // city = t('feature.track_time_duration.third_ring.unknown')
            }
        }
        else {
            city = `${Math.abs(parseInt(scenario.extra.lat))}°${parseInt(scenario.extra.lat) < 0 ? 'S' : 'N'} ${Math.abs(parseInt(scenario.extra.lng))}°${parseInt(scenario.extra.lng) < 0 ? 'W' : 'E'}`//t('feature.track_time_duration.third_ring.unknown')
        }
        return city
    }

    function locationIcon() {
        if (!health.windows || !user.isLogin) return null
        var scenario = getScenario(health.windows, health.mode)
        if ((health.mode == 'DAY' || health.mode == 'NIGHT') && scenario.extra.choose_location) {
            return <View className="navi-streak"
                onClick={() => {
                    global.chooseLocation()
                }}
                style={{ height: 44, marginTop: systemInfo.statusBarHeight, }}>
                <View style={{ width: rpxToPx(16) }} />
                <IconMap color='#000' width={20} />
                <View style={{ width: rpxToPx(4) }} />
                <Text className="h34 bold" style={{ color: '#000' }}>{getCity()}</Text>
            </View>
        }
        return null
    }

    function onScroll(e) {
        scrollTop = e.detail.scrollTop

        setShowStreak(scrollTop < 20)
    }

    if (!loaded)
        return <View />

    return <View style={{ flex: 1, position: 'relative' }}>
        <View style={{ height: navigationBarHeight, backgroundColor: MainColorType.g05 }} />
        <View className="navi-bar" style={{ height: navigationBarHeight, zIndex: 1000, backgroundColor: showCalendar ? '#fff' : MainColorType.g05 }}>
            <View className="navi-streak" style={{
                height: 44,
                marginTop: systemInfo.statusBarHeight,
                alignItems: 'center',
                justifyContent: 'center',
                paddingLeft: 0,
                fontWeight: 'bold',
                fontSize: 17
            }} >{health.title}</View>

            {
                showStreak && steakIcon()
            }
            {
                locationIcon()
            }

            <View style={{
                position: 'absolute',
                left: 60,
                right: 60,
                bottom: 0,
                height: 44,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
            }}>
                <HeaderCircadian />
            </View>


        </View>
        <ClockNew onScroll={onScroll}>
            {
                showCalendar && <Streak testInfo={null}
                    // top={scrollTop}
                    top={navigationBarHeight}
                    dismiss={() => {
                        setShowCalendar(false)
                    }}
                    confirm={() => { }}>
                    <View style={{ display: 'flex', flexDirection: 'column' }}>
                        {/* <View style={{ height: navigationBarHeight }} /> */}
                        <Calendar year={2024} month={new Date().getMonth() + 1} mode={health.mode} />
                    </View>
                </Streak>
            }
        </ClockNew>
        {
            showModal && <AddLabel labels={labels}
                window='ACTIVE'
                disMiss={() => setShowModal(false)}
                op_page='SCHEDULE_ACTIVE_SLEEP'
                // onlyCheck={true}
                // schedules={[]}
                confirm={(res) => {

                    if ((res as any).result) {
                        global.refreshWindow()
                        setShowModal(false)
                        // dispatch(setSchedules((res as any).schedules))
                        // dispatch(setFooter((res as any).footer))
                        // setList((res as any).schedules)
                        // setErrors([])
                    }
                    else {
                        showAlert({
                            title: t('health.schedule_conflict'),
                            content: t('health.conflict_desc'),
                            showCancel: false,
                            confirmText: t('health.check_conflict'),
                            confirm: () => {
                                setTimeout(() => {
                                    setShowModal(false)
                                }, 1000)

                                if ((res as any).show_conflict_dialog) {
                                    jumpPage('/_health/pages/schedules?mode=' + '&error=' + JSON.stringify(res))
                                }
                                else {
                                    jumpPage('/_health/pages/schedules?mode=' + health.mode + '&error=' + JSON.stringify(res))
                                }


                                // jumpPage(`./schedules?mode=&schedules=${JSON.stringify((res as any).schedules)}&errors=${JSON.stringify((res as any).error_messages)}`)
                            }
                        })

                        // setList((res as any).schedules)
                        // dispatch(setFooter((res as any).footer))
                        // setErrors((res as any).error_messages ? (res as any).error_messages : [])
                    }

                }}
                color={MainColorType.active} />
        }


    </View>
}