import { useTranslation } from "react-i18next";
import TitleView from "./TitleView";
import Taro from "@tarojs/taro";
import { setScenario, setStep } from "@/store/scenario";
import { updateScenario } from "@/store/time";
import { jumpPage } from "../hooks/Common";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useRef, useState } from "react";
import { durationDatas, durationIndex, getColor, getDurationTitle } from "../hooks/Console";
import { PageContainer, View } from "@tarojs/components";
import PickerViews from "@/components/input/PickerViews";
import Modal from "@/components/layout/Modal.weapp";
import { ColorType } from "@/context/themes/color";
import { getPlans, updateRecord } from "@/services/trackTimeDuration";
import showActionSheet from "@/components/basic/ActionSheet";
import { chooseMode, initTarget, updateStep } from "@/store/set_target";


let GradientText
let useNavigation;
let useActionSheet;

if (process.env.TARO_ENV == 'rn') {
    GradientText = require('@/components/basic/GradientText').default
    useNavigation = require("@react-navigation/native").useNavigation
    useActionSheet = require('@expo/react-native-action-sheet').useActionSheet
}

export default function ClockHeader(props: { homeData: any }) {
    const user = useSelector((state: any) => state.user);
    const time = useSelector((state: any) => state.time);
    const ring = useSelector((state: any) => state.ring);
    const [fastPickerValue, setFastPickerValue] = useState([0, 0])
    const [sleepPickerValue, setSleepPickerValue] = useState([0, 0])
    const [fastDuration, setFastDuration] = useState<number>(0);
    const [sleepDuration, setSleepDuration] = useState<number>(0);
    const [showDurationPicker, setShowDurationPicker] = useState(false)
    const [showEditPicker, setShowEditPicker] = useState(false)
    const [currentRecord, setCurrentRecord] = useState(null)
    const [isFast, setIsFast] = useState(true)
    const common = useSelector((state: any) => state.common);
    const durationPickerRef = useRef(null)
    const isFastFirst = true;


    const dispatch = useDispatch();
    const { t } = useTranslation()
    let navigation, showActionSheetWithOptions;
    if (useNavigation) {
        navigation = useNavigation()
        showActionSheetWithOptions = useActionSheet()
    }

    useEffect(() => {
        if (props.homeData) {
            setCurrentRecord(props.homeData.current_record)
            getStateDetail()
        }

    }, [props.homeData])

    function getStateDetail() {
        var current_record = props.homeData.current_record
        if (current_record.fast) {
            var fastCount = current_record.fast.target_end_time - current_record.fast.target_start_time
            setFastDuration(fastCount)
            setFastPickerValue(durationIndex(current_record.fast.target_start_time, current_record.fast.target_end_time, common))
        }
        if (current_record.sleep) {
            var sleepCount = current_record.sleep.target_end_time - current_record.sleep.target_start_time
            setSleepDuration(sleepCount)
            setSleepPickerValue(durationIndex(current_record.sleep.target_start_time, current_record.sleep.target_end_time, common))
        }

    }

    function tapAddBtn() {
        showActionSheet({
            showActionSheetWithOptions: showActionSheetWithOptions,
            itemList: [
                t('feature.track_time_duration.action_sheet.switch_scenario'),
                t('feature.track_time_duration.action_sheet.suggest_schedule'),
                t('feature.track_time_duration.action_sheet.change_schedule')
            ],
            success: (res) => {
                switch (res) {
                    case 0:
                        if (time.status != 'WAIT_FOR_START') {
                            Taro.showToast({
                                title: t('feature.common.toast.ongoing'),
                                icon: 'none'
                            })
                            return;
                        }
                        jumpPage('/pages/clock/ChooseScenario?trigger_event=SETUP_AFTER_ACCOUNT_CREATION', 'ChooseScenario', navigation, {
                            trigger_event: 'SETUP_AFTER_ACCOUNT_CREATION'
                        })
                        break;
                    case 1:
                        if (time.status != 'WAIT_FOR_START') {
                            Taro.showToast({
                                title: t('feature.common.toast.ongoing'),
                                icon: 'none'
                            })
                            return;
                        }
                        getPlans().then(res => {
                            const data = res as { scenarios: any[] };
                            console.log(data)
                            var targets: any = {}
                            data.scenarios.forEach((item) => {
                                if (item.name == 'FAST') {
                                    if (item.schedule.fast.duration.prev_input) {
                                        item.schedule.fast.duration.last_value = item.schedule.fast.duration.init_value
                                    }
                                    targets.fast = item
                                }
                                else if (item.name == 'SLEEP') {
                                    targets.sleep = item
                                }
                            })
                            dispatch(initTarget(targets))
                            dispatch(updateStep({ step: 0 }))
                            dispatch(chooseMode({ isMixed: ring.current_record.scenario == 'FAST_SLEEP' }))
                            jumpPage(`/pages/clock/Suggest?trigger_event=SETUP_AFTER_ACCOUNT_CREATION`, 'Suggest', navigation, {
                                trigger_event: 'SETUP_AFTER_ACCOUNT_CREATION'
                            })
                        })

                        break;
                    case 2:
                        if (time.status != 'WAIT_FOR_START') {
                            Taro.showToast({
                                title: t('feature.common.toast.ongoing'),
                                icon: 'none'
                            })
                            return;
                        }
                        getPlans().then(res => {
                            const data = res as { scenarios: any[] };
                            console.log(data)
                            var targets: any = {}
                            data.scenarios.forEach((item) => {
                                if (item.name == 'FAST') {
                                    if (item.schedule.fast.duration.prev_input) {
                                        item.schedule.fast.duration.last_value = item.schedule.fast.duration.init_value
                                    }
                                    targets.fast = item
                                }
                                else if (item.name == 'SLEEP') {
                                    targets.sleep = item
                                }
                            })
                            dispatch(initTarget(targets))
                            dispatch(updateStep({ step: 2 }))
                            dispatch(chooseMode({ isMixed: ring.current_record.scenario == 'FAST_SLEEP' }))
                            jumpPage(`/pages/clock/SetGoal?upgrade=true&isSelf=1&trigger_event=SETUP_AFTER_ACCOUNT_CREATION`, 'SetGoal', navigation, {
                                trigger_event: 'SETUP_AFTER_ACCOUNT_CREATION',
                                upgrade: true,
                                isSelf: 1
                            })
                        })
                        break;
                }
            }
        })
    }

    function durationPickerContent() {
        var color = getColor(currentRecord)
        var title = getDurationTitle(currentRecord, t)
        return <View style={{ color: '#fff', backgroundColor: 'transparent' }}>


            <PickerViews ref={durationPickerRef}
                onChange={durationChange}
                items={durationDatas(common)}
                value={isFast ? fastPickerValue : sleepPickerValue}
                themeColor={color}
                title={title}
                showBtns={true}
                onCancel={() => {
                    setShowDurationPicker(false)
                }} />
        </View>
    }

    function editPickerContent() {
        return <View style={{ color: '#fff', backgroundColor: 'transparent' }}>
            <PickerViews ref={durationPickerRef}
                onChange={durationChange}
                items={durationDatas(common)}
                value={isFast ? fastPickerValue : sleepPickerValue}
                themeColor={isFast ? ColorType.fast : ColorType.sleep}
                title={isFast ? t('feature.track_time_duration.action_sheet.edit_fasting_goal') :
                    t('feature.track_time_duration.action_sheet.edit_sleeping_goal')}
                showBtns={true}
                onCancel={() => {
                    setShowEditPicker(false)
                }} />
        </View>
    }

    function durationChange(e) {
        // debugger
        var count = (e[0] + common.duration.min) * 60 + e[1] * common.duration.step
        // var count = (e[0] + 1) * 60 + e[1] * 5
        if (showDurationPicker) {
            global.changeTargetDuration(count, isFast)
        }
        else {
            var params: any = {}
            if (isFast) {
                params = {
                    fast: {
                        target_duration: count * 60 * 1000
                    }
                }
            }
            else {
                params = {
                    sleep: {
                        target_duration: count * 60 * 1000
                    }
                }
            }
            updateRecord({
                ...params
            }, (currentRecord as any).id).then(res => {
                global.indexPageRefresh()
                if (global.refreshStreaks){
                    global.refreshStreaks()
                }
            }).catch(e => {

            })
        }
        setShowDurationPicker(false)
        setShowEditPicker(false)
    }

    function modalContent() {
        if (showDurationPicker || showEditPicker) {
            return <Modal
                testInfo={null}
                dismiss={() => {
                    setShowDurationPicker(false)
                    setShowEditPicker(false)
                }}
                confirm={() => { }}>
                {
                    showDurationPicker ? durationPickerContent() : editPickerContent()
                }
            </Modal>

        }
        return <View />
    }

    /*function headerView() {
        return <TitleView title={t('page.metric.title')} showAddBtn={loaded && !showErrorPage ? true : false} onClick={addBtnClick}>
        </TitleView>
    }*/


    return <View>
        <TitleView title={t('page.clock.title')} onClick={tapAddBtn} showAddBtn={user.isLogin ? true : false}>

        </TitleView>
        {
            modalContent()
        }
    </View>
}
