import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { View, Image, ScrollView } from "@tarojs/components";
import './ClockIndex.scss'
import TabBar from "@/components/navigation/TabBar";
import { IconClose, IconNext } from "@/components/basic/Icons";
import { rpxToPx } from "@/utils/tools";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { homeInfo } from "@/services/health";
import dayjs from "dayjs";
import { setActions, setEvents, setTimeData } from "@/store/record";
import { TimeFormatter } from "@/utils/time_format";
import { getInfo } from "@/services/user";
import Taro from "@tarojs/taro";
import ChooseActions from "./components/choose_actions";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import { BASE_IMG_URL } from "@/services/http/api";
import { useTranslation } from "react-i18next";
import NoData from "@/_health/components/no_data";

var timer
let useNavigation,LinearGradient;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
    LinearGradient = require('react-native-linear-gradient').default
}
export default function ClockIndex() {
    const systemInfo: any = Taro.getWindowInfo ? Taro.getWindowInfo() : Taro.getSystemInfoSync();
    // const navigationBarHeight = systemInfo.statusBarHeight + 44;
    const screenHeight = systemInfo.screenHeight

    const user = useSelector((state: any) => state.user);
    const record = useSelector((state: any) => state.record);
    const [loaded, setLoaded] = useState(false)
    const [showRetry, setShowRetry] = useState(false)
    const [home, setHome] = useState<any>(null)
    const [count, setCount] = useState(0)
    const [currentTimeData, setCurrentTimeData] = useState<any>(null)
    const [showChoose, setShowChoose] = useState(false)
    const [selScenario, setSelScenario] = useState('')
    const [scenarios, setScenarios] = useState<any>([])
    const dispatch = useDispatch();
    const { t } = useTranslation()
    global.dispatch = dispatch;

    dayjs.locale(global.language == 'en' ? 'en' : 'zh-cn');

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

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

    function getHomeData() {
        homeInfo().then(res => {
            setLoaded(true)
            setHome(res)
            setCount(1)
            setScenarios((res as any).scenarios ?? [])
            dispatch(setEvents((res as any).events))
            dispatch(setActions((res as any).actions))
            setShowRetry(false)
        }).catch(e => {
            setShowRetry(true)
        })
    }

    useEffect(() => {
        getInfo()
        Taro.eventCenter.on('refreshClockIndex', getHomeData)
        timer = setInterval(() => {
            setCount(pre => pre + 1)
        }, 1000)
        return () => {
            clearInterval(timer)
            Taro.eventCenter.off('refreshClockIndex')
        }
    }, [])
    useEffect(() => {
        getTime()
    }, [count])

    useEffect(() => {
        if (currentTimeData) {
            dispatch(setTimeData(currentTimeData))
        }
    }, [currentTimeData])

    function tapItem(index) {
        if (!user.isLogin) {
            jumpPage('/_account/pages/ChooseAuth', 'ChooseAuth', navigation)
            return
        }
        var scenarioObj = scenarios[index]
        switch (scenarioObj.scenario) {
            case 'MEAL':
                setShowChoose(true)
                setSelScenario('MEAL')
                break;
            case 'ACTIVITY':
                setShowChoose(true)
                setSelScenario('ACTIVITY')
                break;
            case 'FAST':
                jumpPage(`/_record/pages/time_record?scenario=FAST`)
                break
            case 'SLEEP':
                jumpPage(`/_record/pages/time_record?scenario=SLEEP`)
                break
            case 'METRIC':
                jumpPage('/pages/metric/Metric')
                break
            case 'MOVE':
                jumpPage('/_health/pages/move')
                break;
        }
    }

    function getTime() {
        if (!home) return
        var now = dayjs().format('HH:mm')
        for (var i = 0; i < home.time_messages.length; i++) {
            var obj = home.time_messages[i]
            if (now >= obj.start_time && now < obj.end_time) {
                setCurrentTimeData(obj)
                return
            }
        }
        setCurrentTimeData(home.time_messages[home.time_messages.length - 1])
    }

    function getBackground() {
        var time = record.time
        if (!time) return '#fff'
        const { background_colors } = time
        if (!background_colors) {
            return '#fff'
        }
        else if (background_colors.length == 1) {
            return background_colors[0]
        }
        return `linear-gradient(to bottom, ${background_colors[0]}, ${background_colors[1]})`
    }

    function itemTime(item) {
        if (item.event && item.event.status == 'OG') {
            return TimeFormatter.countdown(item.event.time.start_timestamp)
        }
        return ''
    }



    if (!loaded && showRetry) return <NoData refresh={
        () => {
            getHomeData()
        }
    } />

    function bgView() {
        if (process.env.TARO_ENV == 'weapp') {
            return <View className="main_bg" style={{ background: getBackground() }} />
        }
        var time = record.time
        if (!time) return <View />
        const { background_colors } = time
        if (!background_colors) {
            return <View />
        }
        else if (background_colors.length == 1) {
            return <View />
        }
        return <LinearGradient style={{
            position: 'absolute',
            left: 0,
            top: 0,

            width: rpxToPx(750),
            height: screenHeight,
            zIndex: 0,
            pointerEvents: 'none'
        }}
            colors={[background_colors[0], background_colors[1]]}
            start={{ x: 0, y: 0 }}
            end={{ x: 0, y: 1 }} pointerEvents="none" />
    }

    if (!loaded) return <View />

    return <View style={{ position: 'relative' }}>
        {
            bgView()
        }
        <ScrollView style={{ height: process.env.TARO_ENV == 'weapp' ? '100vh' : '100%' }} scrollY><View style={{ position: 'relative', overflow: 'hidden', minHeight: process.env.TARO_ENV == 'weapp' ? '101vh' : '100%' }}>

            <View className="h60 bold" style={{ marginLeft: rpxToPx(52), marginTop: rpxToPx(212) }}>{record.time ? record.time.greeting : ''}</View>
            <View style={{ display: 'flex', flexDirection: 'row' }}>
                <View className="h44 bold" style={{ marginLeft: rpxToPx(52), marginTop: rpxToPx(66), marginBottom: rpxToPx(32), position: 'relative', paddingBottom: rpxToPx(20) }}>{t('health.check_in')}
                    <View className="tab_border_line" />
                </View>
            </View>


            <View className="operate_panel">
                {
                    scenarios.map((item, index) => {
                        return <NewButton type={NewButtonType.custom}
                            key={index}
                            onClick={() => {
                                tapItem(index)

                            }}>
                            <View className="operate_card" >
                                <View className="h36 bold">{item.title}</View>
                                <View className="h50 bold">{itemTime(item)}</View>
                                <View style={{ flex: 1 }} />
                                <View style={{ display: 'flex',flexDirection:'row', justifyContent: 'space-between', alignItems: 'center', }}>
                                    <Image src={item.icon} style={{ width: rpxToPx(48), height: rpxToPx(48) }} />
                                    <Image src={item.action_icon} style={{ width: rpxToPx(36), height: rpxToPx(36) }} />
                                </View>
                            </View>
                        </NewButton>
                    })
                }
            </View>
            <View style={{ height: 100 }} />


        </View>
        </ScrollView>
        {
            showChoose && <ChooseActions
                close={() => {
                    setShowChoose(false)
                }}
                quick={() => {
                    jumpPage(`/_record/pages/log_record?scenario=${selScenario}&quick=1`)
                }}
                chooseImg={(array) => {
                    jumpPage(`/_record/pages/log_record?scenario=${selScenario}&imgs=${JSON.stringify(array)}`)
                }}
                chooseText={() => {
                    jumpPage(`/_record/pages/log_record?scenario=${selScenario}&only_text=1`)
                }}
            />
        }
        {
            process.env.TARO_ENV == 'weapp' && <TabBar index={0} />
        }
    </View>
}