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 { updateRecord } from "@/services/trackTimeDuration";


let GradientText
let useNavigation;

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

export default function ClockHeader(props: { homeData: any }) {
    const user = useSelector((state: any) => state.user);
    const time = useSelector((state: any) => state.time);
    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;
    if (useNavigation) {
        navigation = useNavigation()
    }

    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() {
        Taro.showActionSheet({
            itemList: [
                t('feature.track_time_duration.action_sheet.switch_scenario'),
                t('feature.track_time_duration.action_sheet.change_schedule')
            ]
        }).then(res => {
            switch (res.tapIndex) {
                case 1:
                    if (time.status != 'WAIT_FOR_START') {
                        Taro.showToast({
                            title: t('feature.common.toast.ongoing'),
                            icon: 'none'
                        })
                        return;
                    }
                    if (time.scenario == 'FAST_SLEEP') {
                        dispatch(setStep(isFastFirst ? 'fast' : 'sleep'))
                    }
                    else if (time.scenario == 'SLEEP') {
                        dispatch(setStep('sleep'))
                    }
                    else {
                        dispatch(setStep('fast'))
                    }
                    jumpPage('/pages/clock/SetSchedule', 'SetSchedule', navigation)
                    break;
                case 0:
                    if (time.status != 'WAIT_FOR_START') {
                        Taro.showToast({
                            title: t('feature.common.toast.ongoing'),
                            icon: 'none'
                        })
                        return;
                    }
                    jumpPage('/pages/clock/ChooseScenario', 'ChooseScenario', navigation)
                    break;
            }
        })
            .catch(err => {
                console.log(err.errMsg)
            })
    }


    function tapAddBtn2() {
        var data = props.homeData.fast_sleep
        var status = data.current_record.status
        var itemList: any = []
        itemList.push(t('feature.track_time_duration.action_sheet.set_new_goals'))
        // if (status == 'WAIT_FOR_START') {
        //     itemList.push(t('feature.track_time_duration.action_sheet.set_new_goals'))
        //     itemList.push(t('feature.track_time_duration.action_sheet.set_fast_goal'))
        //     itemList.push(t('feature.track_time_duration.action_sheet.set_sleep_goal'))
        // }
        // else if (status == 'ONGOING1') {
        //     itemList.push(t('feature.track_time_duration.action_sheet.set_sleep_goal'))
        //     itemList.push(t('feature.track_time_duration.action_sheet.edit_fasting_goal'))
        // }
        // else if (status == 'ONGOING2') {
        //     itemList.push(t('feature.track_time_duration.action_sheet.edit_sleeping_goal'))
        //     itemList.push(t('feature.track_time_duration.action_sheet.edit_fasting_goal'))
        // }
        // else if (status == 'ONGOING3') {
        //     itemList.push(t('feature.track_time_duration.action_sheet.edit_fasting_goal'))
        // }
        Taro.showActionSheet({
            itemList: itemList
        }).then(res => {
            switch (res.tapIndex) {
                case 0:
                    {
                        if (status == 'WAIT_FOR_START') {
                            dispatch(setStep('fast'))
                            dispatch(updateScenario(data.current_record))
                            dispatch(setScenario(data.scenario));
                            jumpPage('/pages/clock/SetSchedule', 'SetSchedule', navigation)
                        }
                        else {
                            Taro.showToast({
                                title: t('feature.common.toast.ongoing'),
                                icon: 'none'
                            })
                        }
                        // else if (status == 'ONGOING1') {
                        //     setIsFast(false)
                        //     setShowDurationPicker(true)
                        // }
                        // else if (status == 'ONGOING2') {
                        //     setIsFast(false)
                        //     setShowEditPicker(true)
                        // }
                        // else if (status == 'ONGOING3') {
                        //     setIsFast(true)
                        //     setShowEditPicker(true)
                        // }
                    }
                    break;
                case 1:
                    {
                        if (status == 'WAIT_FOR_START') {
                            setIsFast(true)
                            setShowDurationPicker(true)
                        }
                        else if (status == 'ONGOING1') {
                            setIsFast(true)
                            setShowEditPicker(true)
                        }
                        else if (status == 'ONGOING2') {
                            setIsFast(true)
                            setShowEditPicker(true)
                        }
                    }
                    break;
                case 2: {
                    if (status == 'WAIT_FOR_START') {
                        Taro.showToast({
                            title: t('feature.track_time_duration.common.start_fasting_first'),
                            icon: 'none'
                        })
                    }
                }
            }
        })
    }

    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()
            }).catch(e => {

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

    function modalContent() {
        if (showDurationPicker || showEditPicker) {
            if (process.env.TARO_ENV == 'weapp') {
                return <Modal
                    testInfo={null}
                    dismiss={() => {
                        setShowDurationPicker(false)
                        setShowEditPicker(false)
                    }}
                    confirm={() => { }}>
                    {
                        showDurationPicker ? durationPickerContent() : editPickerContent()
                    }
                </Modal>
            }
            else if (process.env.TARO_ENV == 'rn') {
                return <PageContainer style={{ backgroundColor: '#1c1c1c' }}
                    // overlayStyle='background-color:rgba(0,0,0,0.9)'
                    // custom-style='background-color:#1c1c1c'
                    overlayStyle={{ backgroundColor: 'rgba(0,0,0,0.9)' }}
                    customStyle={{ backgroundColor: '#1c1c1c' }}
                    closeOnSlideDown={false}
                    onBeforeEnter={() => {
                        Taro.hideTabBar();
                    }}
                    onBeforeLeave={() => {
                        Taro.showTabBar();
                    }}
                    onClick={() => { alert('b') }}
                    onClickOverlay={() => { alert('a') }}
                    onAfterLeave={() => { setShowDurationPicker(false); setShowEditPicker(false) }}
                    show={showDurationPicker} round={true} overlay={true} position='bottom'
                >
                    {
                        showDurationPicker ? durationPickerContent() : editPickerContent()
                    }
                </PageContainer>
            }
        }
        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>
}