import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { View, Image, ScrollView, Swiper, SwiperItem, Block } 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, useRef, useState } from "react";
import { homeInfo, windows } from "@/services/health";
import dayjs from "dayjs";
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';

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";
import IndexTab from "./components/index_tab";
import TimeRecord from "@/_record/pages/time_record";
import RecordTime from "./components/record_time";
import RecordLog from "./components/record_log";
import PickerCard from "@/_record/components/picker_card";
import LogPublish from "./components/log_publish";
import RecordTimeResult from "./components/record_time_result";
import { setFastWithSleep, setWindows } from "@/store/health";

var timer
let useNavigation, LinearGradient;
let pickerConfirm;
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 safeAreaInsets = systemInfo.safeArea; // 获取安全区域信息

    // 计算底部安全区域的高度
    const bottomSafeAreaHeight = systemInfo.windowHeight - safeAreaInsets.bottom;

    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 [selTag, setSelTag] = useState<any>(null)
    const [scenarios, setScenarios] = useState<any>([])
    const [tabs, setTabs] = useState<any>([])
    const dispatch = useDispatch();
    const { t } = useTranslation()
    global.dispatch = dispatch;

    const [showDatePicker, setShowDatePicker] = useState(false)
    const [showDurationPicker, setShowDurationPicker] = useState(false)
    const [showEndDatePicker, setShowEndDatePicker] = useState(false)
    const [pickerTitle, setPickerTitle] = useState('')
    const [pickerValue, setPickerValue] = useState<any>(null)
    const [showLogPublish, setShowLogPublish] = useState(false)
    const startPickerRef = useRef(showDatePicker)
    const endPickerRef = useRef(showEndDatePicker)
    const durationPickerRef = useRef(showDurationPicker)

    const [tags, setTags] = useState<any>([])
    const [addTag, setAddTag] = useState(false)

    const [showTimeResult, setShowTimeResult] = useState(false)
    const [timeResult, setTimeResult] = useState<any>(null)

    const [current, setCurrent] = useState(0)


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

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

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

    useEffect(() => {
        startPickerRef.current = showDatePicker
        endPickerRef.current = showEndDatePicker
        durationPickerRef.current = showDurationPicker
    }, [showDatePicker, showDurationPicker, showEndDatePicker])

    function getHomeData() {
        getWindows()
        homeInfo().then(res => {
            setLoaded(true)
            setHome(res)
            setCount(1)

            dispatch(setEvents((res as any).events))
            dispatch(setActions((res as any).actions))
            if ((res as any).scenarios) {
                setScenarios((res as any).scenarios)
                var active_scenario = (res as any).active_scenario
                setTabs((res as any).scenarios.map(((item, index) => {
                    if (item.scenario == active_scenario) {
                        setCurrent(index)
                    }
                    return item.title
                })))
            }
            setShowRetry(false)
        }).catch(e => {
            setShowRetry(true)
        })
    }

    function getWindows() {
        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))

        }).catch(e => {
        })
    }

    useEffect(() => {
        getInfo()
        Taro.eventCenter.on('refreshClockIndex', getHomeData)
        timer = setInterval(() => {
            if (startPickerRef.current || endPickerRef.current || durationPickerRef.current) {
                return
            }
            // console.log(showDatePicker , showDurationPicker , showEndDatePicker)
            setCount(pre => pre + 1)
        }, 1000)
        return () => {
            clearInterval(timer)
            Taro.eventCenter.off('refreshClockIndex')
        }
    }, [])

    useEffect(() => {
        Taro.eventCenter.trigger('hideTab', showChoose)
    }, [showChoose])

    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`, 'TimeRecord', navigation, {
                    scenario: 'FAST'
                })
                break
            case 'SLEEP':
                jumpPage(`/_record/pages/time_record?scenario=SLEEP`, 'TimeRecord', navigation, {
                    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 ''
    }

    function showPicker(type, title, value, confirm) {
        setPickerTitle(title)
        setPickerValue(value)
        // setPickerFunc(confirm)
        pickerConfirm = confirm
        switch (type) {
            case 'duration':
                setShowDurationPicker(true)
                break
            case 'start':
                setShowDatePicker(true)
                break
            case 'end':
                setShowEndDatePicker(true)
                break
        }
    }

    function hidePicker() {
        setShowDatePicker(false)
        setShowEndDatePicker(false)
        setShowDurationPicker(false)
    }


    const array = global.language == 'en' ? ['Eat', 'Workout', 'Fast', 'Sleep'] : ['饮食', '运动', '断食', '睡眠']
    if (!loaded && showRetry) return <View style={{ position: 'relative' }}>
        <View style={{ height: navigationBarHeight }} />
        <IndexTab items={array} current={current} onChanged={(index) => {
            setCurrent(index)
        }} />
        <NoData refresh={
            () => {
                getHomeData()
            }
        } />

    </View>

    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" />
    }

    function swiperHeight() {
        return screenHeight - navigationBarHeight - rpxToPx(94) - rpxToPx(112) - bottomSafeAreaHeight + 4
    }

    if (!loaded) return <View />

    return <View style={{ position: 'relative' }}>
        {
            bgView()
        }
        <View style={{ height: navigationBarHeight }} />
        <IndexTab items={tabs} current={current} onChanged={(index) => {
            setCurrent(index)
        }} />
        <Swiper style={{ height: swiperHeight(), width: rpxToPx(750) }} current={current} onChange={e => {
            setCurrent(e.detail.current)
        }}>
            {
                scenarios.map((item, index) => {
                    return <SwiperItem key={index}>
                        {
                            item.scenario == 'FAST' && <RecordTime scenario="FAST"
                                event={item.event}
                                theme_color={item.theme_color}
                                contentHeight={swiperHeight()}
                                showPicker={showPicker}
                                hidePicker={hidePicker}
                                complete={info => {
                                    setTimeResult(info)
                                    setSelScenario('FAST')
                                    setShowTimeResult(true)
                                }}
                                count={count} />
                        }
                        {
                            item.scenario == 'SLEEP' && <RecordTime scenario="SLEEP"
                                event={item.event}
                                theme_color={item.theme_color}
                                contentHeight={swiperHeight()}
                                showPicker={showPicker} hidePicker={hidePicker}
                                complete={info => {
                                    setTimeResult(info)
                                    setSelScenario('SLEEP')
                                    setShowTimeResult(true)
                                }}
                                count={count} />
                        }
                        {
                            item.scenario == 'MEAL' && <RecordLog scenario="MEAL"
                                tags={item.tags}
                                contentHeight={swiperHeight()}
                                showPublish={(scenario, tag, tags, addTag) => {
                                    setAddTag(addTag)
                                    setShowLogPublish(true)
                                    setSelScenario(scenario)
                                    setSelTag(tag)
                                    setTags(tags)
                                }} />
                        }
                        {
                            item.scenario == 'ACTIVITY' && <RecordLog
                                tags={item.tags}
                                scenario="ACTIVITY"
                                contentHeight={swiperHeight()}
                                showPublish={(scenario, tag, tags, addTag) => {
                                    setAddTag(addTag)
                                    setShowLogPublish(true)
                                    setSelScenario(scenario)
                                    setSelTag(tag)
                                    setTags(tags)
                                }} />
                        }
                    </SwiperItem>
                })
            }
            {/* <SwiperItem>
                <RecordTime scenario="FAST"
                    contentHeight={swiperHeight()}
                    showPicker={showPicker}
                    hidePicker={hidePicker}
                    complete={info => {
                        setTimeResult(info)
                        setScenarios('FAST')
                        setShowTimeResult(true)
                    }}
                    count={count} />
            </SwiperItem>
            <SwiperItem>
                <RecordTime scenario="SLEEP"
                    contentHeight={swiperHeight()}
                    showPicker={showPicker} hidePicker={hidePicker}
                    complete={info => {
                        setTimeResult(info)
                        setScenarios('SLEEP')
                        setShowTimeResult(true)
                    }}
                    count={count} />
            </SwiperItem>
            <SwiperItem>
                <RecordLog scenario="MEAL" contentHeight={swiperHeight()} showPublish={(scenario, tag, tags, addTag) => {
                    setAddTag(addTag)
                    setShowLogPublish(true)
                    setSelScenario(scenario)
                    setSelTag(tag)
                    setTags(tags)
                }} />
            </SwiperItem>
            <SwiperItem>
                <RecordLog scenario="ACTIVITY" contentHeight={swiperHeight()} showPublish={(scenario, tag, tags, addTag) => {
                    setAddTag(addTag)
                    setShowLogPublish(true)
                    setSelScenario(scenario)
                    setSelTag(tag)
                    setTags(tags)
                }} />
            </SwiperItem> */}
        </Swiper>
        {
            showChoose && <ChooseActions
                close={() => {
                    setShowChoose(false)
                }}
                quick={() => {
                    jumpPage(`/_record/pages/log_record?scenario=${selScenario}&quick=1`, 'LogRecord', navigation, {
                        scenario: selScenario,
                        quick: 1
                    })
                }}
                chooseImg={(array) => {
                    jumpPage(`/_record/pages/log_record?scenario=${selScenario}&imgs=${JSON.stringify(array)}`, 'LogRecord', navigation, {
                        scenario: selScenario,
                        imgs: JSON.stringify(array)
                    })
                }}
                chooseText={() => {
                    jumpPage(`/_record/pages/log_record?scenario=${selScenario}&only_text=1`, 'LogRecord', navigation, {
                        scenario: selScenario,
                        only_text: 1
                    })
                }}
            />
        }
        <Block>
            {
                showDurationPicker && <PickerCard onClose={() => { setShowDurationPicker(false) }}
                    value={pickerValue}
                    type="duration"
                    title={pickerTitle}
                    onConfirm={(e) => {
                        // pickerFunc(e)
                        pickerConfirm(e)
                    }}
                />
            }
        </Block>
        <Block>
            {
                showDatePicker && <PickerCard onClose={() => { setShowDatePicker(false) }}
                    value={pickerValue}
                    type="datetime"
                    title={pickerTitle}
                    onConfirm={(e) => {
                        // pickerFunc(e)
                        pickerConfirm(e)
                    }}
                />
            }
        </Block>
        <Block>
            {
                showEndDatePicker && <PickerCard onClose={() => { setShowEndDatePicker(false) }}
                    value={pickerValue}
                    type="datetime"
                    title={pickerTitle}
                    onConfirm={(e) => {
                        // pickerFunc(e)
                        pickerConfirm(e)
                    }}
                />
            }
        </Block>
        <Block>
            {
                showLogPublish && <LogPublish scenario={selScenario}
                    tags={tags}
                    tag={selTag}
                    addTag={addTag}
                    onClose={() => {
                        setShowLogPublish(false)
                    }} />
            }
        </Block>
        <Block>
            {
                showTimeResult && <RecordTimeResult
                    showPicker={showPicker}
                    hidePicker={hidePicker}
                    onClose={() => setShowTimeResult(false)}
                    scenario={selScenario}
                    info={timeResult}
                    goEat={() => {
                        setCurrent(0)
                        setShowTimeResult(false)
                    }}
                />
            }
        </Block>
        {
            process.env.TARO_ENV == 'weapp' && <TabBar index={0} />
        }
    </View>
}