import { View, Text, Image, PageContainer } from "@tarojs/components";
import './TotalTime.scss'
import { useTranslation } from "react-i18next";
import { ColorType } from "@/context/themes/color";
import { rpxToPx } from "@/utils/tools";
import { TimeFormatter } from "@/utils/time_format";
import Modal from "@/components/layout/Modal.weapp";
import { useEffect, useRef, useState } from "react";
import { durationDatas, durationIndex, getColor, getDurationTitle } from "../hooks/Console";
import PickerViews from "@/components/input/PickerViews";
import { useSelector } from "react-redux";
import Taro from "@tarojs/taro";
import { updateRecord } from "@/services/trackTimeDuration";

export default function TotalTime(props: { record: any }) {
    const [showDurationPicker, setShowDurationPicker] = useState(false)
    const [fastPickerValue, setFastPickerValue] = useState([0, 0])
    const [sleepPickerValue, setSleepPickerValue] = useState([0, 0])
    const [showEditPicker, setShowEditPicker] = useState(false)
    const [count, setCount] = useState(0)
    const common = useSelector((state: any) => state.common);
    const [isFast, setIsFast] = useState(true)
    const durationPickerRef = useRef(null)
    const { t } = useTranslation()

    useEffect(() => {
        getStateDetail()
        setCount((pre) => pre + 1)
    }, [props.record])

    function getStateDetail() {
        var current_record = props.record
        if (current_record.fast)
            setFastPickerValue(durationIndex(current_record.fast.target_start_time, current_record.fast.target_end_time, common))
        if (current_record.sleep)
            setSleepPickerValue(durationIndex(current_record.sleep.target_start_time, current_record.sleep.target_end_time, common))
    }

    function sleepCompleteStatus() {
        if (props.record.sleep.status == "NOT_STARTED") {
            return t('feature.common.not_started')
        }
        else if (props.record.sleep.status == 'NOT_COMPLETED') {
            return t('feature.common.not_completed')
        }
        return TimeFormatter.durationFormate(props.record.sleep.real_start_time, props.record.sleep.real_end_time)
    }

    function fastGoingText() {
        if (props.record.status == 'WAIT_FOR_START') {
            return '00:00:00'
        }
        return TimeFormatter.formateTimeNow(props.record.fast.real_start_time)
    }

    function fastEndText() {
        if (props.record.status == 'WAIT_FOR_START') {
            return TimeFormatter.formateTimeDifference(new Date().getTime(), new Date().getTime() + props.record.fast.target_end_time - props.record.fast.target_start_time)
        }
        return TimeFormatter.countdown(props.record.fast.target_end_time)
    }

    function sleepGoingText() {
        if (props.record.status == 'WAIT_FOR_START' || props.record.status == 'ONGOING1') {
            return '00:00:00'
        }
        return TimeFormatter.formateTimeNow(props.record.sleep.real_start_time)
    }

    function sleepEndText() {
        if (props.record.status == 'WAIT_FOR_START' || props.record.status == 'ONGOING1') {
            return TimeFormatter.formateTimeDifference(new Date().getTime(), new Date().getTime() + props.record.sleep.target_end_time - props.record.sleep.target_start_time)
        }
        return TimeFormatter.countdown(props.record.sleep.target_end_time)
    }

    function setFastDuration(e) {
        setIsFast(true)
        if (disableChange(true)) return
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }
        if (props.record.status == 'WAIT_FOR_START') {
            setShowDurationPicker(true)
        }
        else {
            setShowEditPicker(true)
        }
    }

    function setSleepDuration(e) {

        setIsFast(false)
        if (disableChange(false)) return
        if (process.env.TARO_ENV == 'weapp') {
            e.stopPropagation()
        }

        if (props.record.status == 'WAIT_FOR_START') {
            Taro.showToast({
                title: t('feature.track_time_duration.common.start_fasting_first'),
                icon: 'none'
            })
            return;
        }
        if (props.record.status == 'WAIT_FOR_START' || props.record.status == 'ONGOING1') {
            setShowDurationPicker(true)
        }
        else {
            setShowEditPicker(true)
        }
    }

    function disableChange(isFastStatus) {
        if (props.record.status == 'WAIT_FOR_START') {
            return false;
        }
        if (isFastStatus) {
            if (props.record.status != 'COMPLETED')
                return false;
            return true
        }
        else {
            if (props.record.status == 'ONGOING3' || props.record.status == 'COMPLETED') {
                return true
            }
            return false;
        }
    }

    function fastOtherStatus() {
        return <View>
            <View className="cell_full" >
                <Text className="cell_title" style={{ opacity: 0.2 }}>已进行</Text>
                <Text className="cell_value"
                    style={{
                        color: props.record.status == 'WAIT_FOR_START' ?
                            '#fff' : ColorType.fast,
                        opacity: props.record.status == 'WAIT_FOR_START' ? 0.2 : 1
                    }}>{fastGoingText()}</Text>
            </View>
            <View className="cell_line" style={{ height: 1 }} />
            <View className="cell_full" >
                <Text className="cell_title" style={{ opacity: 0.2 }}>{new Date().getTime() < props.record.fast.target_end_time ? '距结束' : '已超时'}</Text>
                <Text className="cell_value" style={{ opacity: 0.2 }}>{fastEndText()}</Text>
            </View>
        </View>
    }

    function sleepOtherStatus() {
        return <View>
            <View className="cell_full" >
                <Text className="cell_title" style={{ opacity: 0.2 }}>已进行</Text>
                <Text className="cell_value" style={{
                    color: props.record.status == 'WAIT_FOR_START' || props.record.status == 'ONGOING1' ?
                        '#fff' : ColorType.sleep,
                    opacity: props.record.status == 'WAIT_FOR_START' || props.record.status == 'ONGOING1' ? 0.2 : 1
                }}>{sleepGoingText()}</Text>
            </View>
            <View className="cell_line" style={{ height: 1 }} />
            <View className="cell_full" >
                <Text className="cell_title" style={{ opacity: 0.2 }}>{new Date().getTime() < props.record.sleep.target_end_time ? '距结束' : '已超时'}</Text>
                <Text className="cell_value" style={{ opacity: 0.2 }}>{sleepEndText()}</Text>
            </View>
        </View>
    }

    function durationPickerContent() {
        var color = getColor(props.record)
        var title = getDurationTitle(props.record, 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
            }, props.record.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={() => {

                    }}
                    onBeforeLeave={() => {
                    }}
                    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 />
    }

    return <View style={{ width: rpxToPx(600) }}>
        {
            props.record.fast && <View>
                <Text className="cell_header">断食</Text>
                <View className="cell_bg">
                    {
                        props.record.status == 'COMPLETED' ?
                            <View className="cell_full" >
                                <Text className="cell_title">{t('feature.track_time_duration.console.real_duration')}</Text>
                                <Text className="cell_value" style={{ color: ColorType.fast }}>{TimeFormatter.durationFormate(props.record.fast.real_start_time, props.record.fast.real_end_time)}</Text>
                                {/* <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} /> */}
                            </View> :
                            <View className="cell_full" onClick={setFastDuration}>
                                <Text className="cell_title">{t('feature.track_time_duration.console.target')}</Text>
                                <Text className="cell_value">{TimeFormatter.durationFormate(props.record.fast.target_start_time, props.record.fast.target_end_time)}</Text>
                                {!disableChange(true) && <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />}
                            </View>
                    }
                    <View className="cell_line" style={{ height: 1 }} />
                    {
                        props.record.status == 'COMPLETED' ?
                            <View className="cell_full" onClick={setFastDuration}>
                                <Text className="cell_title" style={{ opacity: 0.2 }}>{t('feature.track_time_duration.console.target')}</Text>
                                <Text className="cell_value" style={{ opacity: 0.2, color: '#fff' }}>{TimeFormatter.durationFormate(props.record.fast.target_start_time, props.record.fast.target_end_time)}</Text>
                                {!disableChange(true) && <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />}
                            </View> :
                            fastOtherStatus()
                    }
                </View>

            </View>
        }
        {
            props.record.sleep && <View style={{ marginTop: 10 }}>
                <Text className="cell_header">睡眠</Text>
                <View className="cell_bg">
                    {
                        // props.record.status == 'COMPLETED' || props.record.status == 'ONGOING3' ?
                        //     <View className="cell_full" >
                        //         <Text className="cell_title">{t('feature.track_time_duration.console.real_duration')}</Text>
                        //         <Text className="cell_value" style={{ color: ColorType.sleep }}>{sleepCompleteStatus()}</Text>
                        //     </View> :
                        <View className="cell_full" onClick={setSleepDuration}>
                            <Text className="cell_title">{t('feature.track_time_duration.console.target')}</Text>
                            <Text className="cell_value">{TimeFormatter.durationFormate(props.record.sleep.target_start_time, props.record.sleep.target_end_time)}</Text>
                            {!disableChange(false) && <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />}
                        </View>
                    }
                    <View className="cell_line" style={{ height: 1 }} />
                    {
                        props.record.status == 'COMPLETED' || props.record.status == 'ONGOING3' ?
                            // <View className="cell_full" onClick={setSleepDuration}>
                            //     <Text className="cell_title" style={{ opacity: 0.2 }}>{t('feature.track_time_duration.console.target')}</Text>
                            //     <Text className="cell_value" style={{ opacity: 0.2, color: '#fff' }}>{TimeFormatter.durationFormate(props.record.sleep.target_start_time, props.record.sleep.target_end_time)}</Text>
                            //     {!disableChange(false) && <Image className="cell_arrow" src={require('@/assets/images/arrow3.png')} />}
                            // </View> 
                            <View className="cell_full" >
                                <Text className="cell_title" style={{ opacity: 0.4 }}>{t('feature.track_time_duration.console.real_duration')}</Text>
                                <Text className="cell_value" style={{ color: ColorType.sleep }}>{sleepCompleteStatus()}</Text>
                            </View>
                            :
                            sleepOtherStatus()
                    }
                </View>
            </View>
        }
        {
            modalContent()
        }

    </View>
}