import { clearTimeRecords, getClockRecords } from "@/services/trackTimeDuration";
import { View, Text, ScrollView, PageMeta, NavigationBar } from "@tarojs/components";
import { usePullDownRefresh, useReachBottom, useReady, useRouter } from "@tarojs/taro";
import { useEffect, useState } from "react";
import Schedule from '@/features/trackTimeDuration/components/Schedule'
import MetricHistory from "@/features/trackSomething/components/MetricHistory";
import ActivityHistory from "@/features/trackSomething/components/ActivityHistory";
import { activityRecords, clearMetricRecords, cleartActivityRecords, metricRecords } from "@/services/trackSomething";
import Taro from "@tarojs/taro";
import Layout from "@/components/layout/layout";
import NoData from "@/components/view/NoData";
import { NaviBarTitleShowType, TemplateType } from "@/utils/types";
import { useSelector } from "react-redux";
import RecordFastSleep from "@/features/trackTimeDuration/components/RecordFastSleep";
import './RecordsHistory.scss'
import { useTranslation } from "react-i18next";
import './RecordsHistory.scss'
import { clearWorkoutRecords, workoutRecords } from "@/services/workout";
import WorkoutHistory from "@/features/workout/WorkoutHistory";
import showAlert from "@/components/basic/Alert";
import { rpxToPx } from "@/utils/tools";

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

export default function Page() {
    const { t } = useTranslation()
    let router
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
        // var title = ''
        // if (router.params.type == 'time') {
        //     title = t('page.clock.title')
        // }
        // else if (router.params.type == 'metric') {
        //     title = t('page.metric.title')
        // }
        // else if (router.params.type == 'workout') {
        //     title = t('page.workout.title')
        // }
        // navigation.setOptions({
        //     headerBackTitle: title
        // });
    }
    else {
        router = useRouter()
    }
    const pageSize = 10
    const [pageIndex, setPageIndex] = useState(1)
    const [records, setRecords] = useState<any[]>([])
    const [counter, setCounter] = useState(0)
    const [timerId, setTimerId] = useState(null)
    const [showErrorPage, setShowErrorPage] = useState(false)
    const { refreshList } = router.params
    const [triggered, setTriggered] = useState(false)
    const [showModal, setShowModal] = useState(false)
    const [modalDetail, setModalDetail] = useState<any>({})
    const [total, setTotal] = useState(0)
    const [isLoading, setIsLoading] = useState(false)
    const [loaded, setLoaded] = useState(false)
    const [summary_stats, setSummaryStats] = useState(null)
    const user = useSelector((state: any) => state.user);
    const [count, setCount] = useState(0)
    const [filterIndex, setFilterIndex] = useState(0)

    useEffect(() => {
        refresh()
    }, [])

    // useEffect(() => {
    //     startTimer();
    //     return () => {
    //         // 在组件卸载时清除定时器
    //         if (timerId) {
    //             clearInterval(timerId);
    //         }
    //     };
    // }, [timerId]);

    useEffect(() => {
        var name = ''
        switch (filterIndex) {
            case 0:
                name = ''
                break;
            case 1:
                name = 'FAST_SLEEP'
                break;
            case 2:
                name = 'FAST'
                break;
            case 3:
                name = 'SLEEP'
                break;
        }
        scenario = name
        setPageIndex(1)
        refresh()

    }, [filterIndex])

    // const startTimer = () => {
    //     // 避免重复启动定时器
    //     if (timerId) {
    //         return;
    //     }

    //     const id = setInterval(() => {
    //         setCounter((prevCounter) => prevCounter + 1);
    //     }, 1000);

    //     setTimerId(id as any);
    // };


    useReady(() => {
        // refresh()
    })

    usePullDownRefresh(() => {
        refresh()
    })

    useReachBottom(() => {
        more()
        // setPageIndex(pageIndex+1)
        // getHistory()
    })

    function refresh() {
        setIsLoading(true)
        setPageIndex(1)
        getHistory(1)
    }

    function more() {
        if (total <= records.length || isLoading) {
            return;
        }
        setIsLoading(true)
        var page = pageIndex + 1
        setPageIndex(page)
        getHistory(page)
    }

    global.reloadWorkoutList = () => {
        workoutRecords(
            {
                page: 1,
                limit: pageIndex * pageSize,
                code: router.params.code
            }
        ).then(res => {
            Taro.stopPullDownRefresh()
            setTriggered(false)
            setLoaded(true)
            setTotal((res as any).total)
            setSummaryStats((res as any).summary_stats)

            setRecords((res as any).data)
            setCount((res as any).total)

            setIsLoading(false)
        })
    }

    function getHistory(page = pageIndex) {
        if (page == 1)
            setTriggered(true)

        if (router.params.type == 'time') {
            getClockRecords({
                page: page,
                limit: pageSize,
                scenario: scenario,
                completed: true,
                // part_completed: true
            }).then(res => {
                Taro.stopPullDownRefresh()
                setTriggered(false)
                setLoaded(true)
                setTotal((res as any).total)
                if (page == 1) {
                    setRecords([])
                    setRecords((res as any).data)
                } else {
                    setRecords(records.concat((res as any).data))
                }
                setIsLoading(false)
            })
        }
        else if (router.params.type == 'activity') {
            activityRecords(
                {
                    page: page,
                    limit: pageSize,
                    code: '_walk'
                }
            ).then(res => {
                Taro.stopPullDownRefresh()
                setTriggered(false)
                setLoaded(true)
                setTotal((res as any).total)
                if (page == 1) {
                    setRecords((res as any).data)
                } else {
                    setRecords(records.concat((res as any).data))
                }
                setIsLoading(false)
            })
        }
        else if (router.params.type == 'metric') {
            metricRecords(
                {
                    page: page,
                    limit: pageSize,
                    code: router.params.code
                }
            ).then(res => {
                Taro.stopPullDownRefresh()
                setTriggered(false)
                setLoaded(true)
                setTotal((res as any).total)
                if (page == 1) {
                    setRecords((res as any).data)
                } else {
                    setRecords(records.concat((res as any).data))
                }
                setIsLoading(false)
            })
        }
        else if (router.params.type == 'workout') {
            workoutRecords(
                {
                    page: page,
                    limit: pageSize,
                    code: router.params.code
                }
            ).then(res => {
                Taro.stopPullDownRefresh()
                setTriggered(false)
                setLoaded(true)
                setTotal((res as any).total)
                setSummaryStats((res as any).summary_stats)
                if (page == 1) {
                    setRecords((res as any).data)
                    setCount((res as any).total)
                } else {
                    setRecords(records.concat((res as any).data))
                }
                setIsLoading(false)
            })
        }

    }

    function removeItem(item) {
        setRecords(records.filter(i => i.id != item.id))
    }

    global.delFastSleep = (item) => {
        removeItem(item)
        global.refrehWeekly()
        global.refreshStreaks()
    }

    global.clearHistory = () => {
        // var page = Taro.getCurrentPages()[0]
        // debugger
        // page.refresh()
        showAlert({
            title: t('feature.common.modal.delete_all_title'),
            content: t('feature.common.modal.delete_all_content'),
            showCancel: true,
            confirm: () => {
                doClear()
            }
        })

    }

    function doClear() {
        if (router.params.type == 'activity') {
            cleartActivityRecords({
                code: '_walk'
            }).then(res => {
                refresh()
                global.refreshActivity()

                // router.params.refreshList()
                // Taro.getCurrentPages()[0].refresh()
            })
        }
        else if (router.params.type == 'metric') {
            clearMetricRecords({
                code: router.params.code
            }).then(res => {
                refresh()
                global.refreshMetric()
                // Taro.getCurrentPages()[0].refresh()
            })
        }
        else if (router.params.type == 'time') {
            clearTimeRecords().then(res => {
                refresh()

                global.refrehWeekly()

                if (global.refreshStreaks) {
                    global.refreshStreaks()
                }
                if (global.checkAccess) {
                    global.checkAccess((res as any).access)
                }

                if (global.indexPageRefresh) {
                    global.indexPageRefresh()
                }
                // global.refreshTime()
                // global.refreshMetric()
                // Taro.getCurrentPages()[0].refresh()
            })
        }
        else if (router.params.type == 'workout') {
            clearWorkoutRecords({
                code: router.params.code
            }).then(res => {
                refresh()
                global.refreshWorkout()
                // global.refreshMetric()
                // Taro.getCurrentPages()[0].refresh()
            })
        }
    }

    function tapFilter(index) {
        setFilterIndex(index)
    }

    function filters() {
        return <View className="filter_bar">
            <View className="filter_bar_item" onClick={() => { tapFilter(0) }}>
                <Text onClick={() => { tapFilter(0) }} className={filterIndex == 0 ? 'filter_item_sel' : 'filter_item_normal'}>{t('feature.track_time_duration.record_fast_sleep.tab_all')}</Text>
            </View>
            <View className="filter_bar_item" onClick={() => { tapFilter(1) }}>
                <Text onClick={() => { tapFilter(1) }} className={filterIndex == 1 ? 'filter_item_sel' : 'filter_item_normal'}>{t('feature.track_time_duration.record_fast_sleep.tab_fast_sleep')}</Text>
            </View>
            <View className="filter_bar_item" onClick={() => { tapFilter(2) }}>
                <Text onClick={() => { tapFilter(2) }} className={filterIndex == 2 ? 'filter_item_sel' : 'filter_item_normal'}>{t('feature.track_time_duration.record_fast_sleep.tab_fast')}</Text>
            </View>
            <View className="filter_bar_item" onClick={() => { tapFilter(3) }}>
                <Text onClick={() => { tapFilter(3) }} className={filterIndex == 3 ? 'filter_item_sel' : 'filter_item_normal'}>{t('feature.track_time_duration.record_fast_sleep.tab_sleep')}</Text>
            </View>
        </View>
    }

    function detail() {
        if (router.params.type == 'time') {
            return <View>
                {
                    process.env.TARO_ENV == 'weapp' && user.test_user && <Text style={{ color: '#fff', position: 'absolute', right: 50, top: 0 }} onClick={() => global.clearHistory()}>删除全部</Text>
                }
                {
                    filters()
                }
                {
                    records.map((item, index) => {
                        return <View className="fast_sleep_item_bg">
                            <RecordFastSleep key={index}
                                data={item}
                                index={index}
                                type='record'
                            />
                        </View>
                    })
                }
            </View>
        }
        if (router.params.type == 'metric') {
            return <MetricHistory records={records} />
        }
        if (router.params.type == 'activity') {
            return <ActivityHistory records={records} />
        }
        if (router.params.type == 'workout') {
            return <WorkoutHistory records={records} count={count} summary_stats={summary_stats} />
        }
    }

    function getTitle() {
        if (router.params.type == 'time') {
            return t('page.records_history.time_title')
        }
        else if (router.params.type == 'metric') {
            return router.params.title
        }
        else if (router.params.type == 'workout') {
            return router.params.title
        }
        else {
            return router.params.title
        }
    }

    return <View style={{ position: 'relative' }}>
        <Layout children={showErrorPage ? <NoData refresh={() => { refresh() }} /> : detail()}
            // title={router.params.title}
            isFastSleepTheme={router.params.type == 'time'}
            secondPage={true}
            titleColor={router.params.themeColor ? router.params.themeColor : '#fff'}
            title={getTitle()}
            type={TemplateType.flex}
            refresh={() => { refresh() }}
            triggered={triggered}
            more={() => { more() }}
            titleShowStyle={NaviBarTitleShowType.scrollToShow}
        />
        {
            loaded && records.length == 0 && <View className="no_records_bg">
                <Text className="no_records">{t('feature.common.no_data.no_record')}</Text>
            </View>
        }

        {
            showModal && modalDetail
        }
    </View>
}