import { recordCheck } from "@/services/trackTimeDuration";
import { View, Text, PickerView } from "@tarojs/components";
import trackTimeService, { machine } from "@/store/trackTimeMachine"
import { useEffect, useState } from "react";
import { TimeFormatter } from "@/utils/time_format";
import TimePickers from '@/components/TimePickers'
import { useSelector } from "react-redux";
import Taro from "@tarojs/taro";
import LimitPickers from '@/components/LimitPickers';
import { endFast, endSleep, startFast, startSleep } from "../actions/TrackTimeActions";
import { durationDatas, durationIndex, pickerDurations } from "../hooks/Console";
import PickerViews from "@/components/PickerViews";
import Modal from "@/components/Modal";
import Stepper from "@/components/Stepper";

export default function Component() {
    const [key, setKey] = useState('');
    const [value, setValue] = useState('');
    const user = useSelector((state: any) => state.user);
    const common = useSelector((state: any) => state.common);
    const [isFast, setIsFast] = useState(true);
    const [fastValues, setFastValues] = useState<number[]>([0, 0]);
    const [sleepValues, setSleepValues] = useState<number[]>([0, 0]);
    const [fastDuration, setFastDuration] = useState<number>(0);
    const [sleepDuration, setSleepDuration] = useState<number>(0);
    const [fastStr, setFastStr] = useState('00:00');
    const [sleepStr, setSleepStr] = useState('00:00');
    const [isOpen, setIsOpen] = useState(false);
    const [showModal, setShowModal] = useState(false);
    const [fastPickerValue, setFastPickerValue] = useState([0, 0])
    const [sleepPickerValue, setSleepPickerValue] = useState([0, 0])
    const [isOpenDurationPicker, setIsOpenDurationPicker] = useState(false)

    // const [pickerValue, setPickerValue] = useState([0,0])

    // const pickerDurations = pickerDurations();

    // console.log(pickerDurations())

    useEffect(() => {
        getStateDetail();
    }, [machine.context.checkData]);

    useEffect(() => {
        getStateDetail();
    }, [machine.context.currentStatus])

    useEffect(() => {
        trackTimeService.onTransition(state => {
            if ((state.value as any).FAST_SLEEP) {
                setKey('FAST_SLEEP');
                setValue((state.value as any).FAST_SLEEP);
            }
            if ((state.value as any).FAST) {
                setKey('FAST');
                setValue((state.value as any).FAST);
            }
            if ((state.value as any).SLEEP) {
                setKey('SLEEP');
                setValue((state.value as any).SLEEP);
            }
        });
    }, []);

    function getStateDetail() {
        var state = trackTimeService.getSnapshot().value
        if ((state as any).FAST_SLEEP) {
            setKey('FAST_SLEEP');
            setValue((state as any).FAST_SLEEP);
            if ((state as any).FAST_SLEEP == 'WAIT_FOR_START' || (state as any).FAST_SLEEP == 'ONGOING3') {
                setIsFast(true);
            }
            else if ((state as any).FAST_SLEEP == 'ONGOING1') {
                setIsFast(false);
            }
        }
        if ((state as any).FAST) {
            setKey('FAST');
            setValue((state as any).FAST);
            setIsFast(true);
        }
        if ((state as any).SLEEP) {
            setKey('SLEEP');
            setValue((state as any).SLEEP);
            setIsFast(false);
        }

        var checkData = machine.context.checkData;
        if (checkData) {
            var current_record = (checkData as any).current_record;
            if (current_record.fast) {
                var fastTime = TimeFormatter.formateHourMinute(current_record.fast.target_start_time,
                    current_record.fast.target_end_time);
                setFastValues(fastTime.split(':').map(x => parseInt(x)));
                setFastStr(fastTime);
                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))
                // setFastPickerValue([fastCount / 60000 / 5 - 12])
            }

            if (current_record.sleep) {
                var sleepTime = TimeFormatter.formateHourMinute(current_record.sleep.target_start_time,
                    current_record.sleep.target_end_time);


                setSleepValues(sleepTime.split(':').map(x => parseInt(x)));

                setSleepStr(sleepTime);

                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))
                // setSleepPickerValue([sleepCount / 60000 / 5 - 12])
            }
        }
    }


    function showPicker() {
        setShowModal(true)
        setIsOpen(true)
        global.set_time = new Date().getTime()
        console.log(global.set_time)
    }

    function hidePicker() {
        setIsOpen(false)
        setTimeout(() => {
            setShowModal(false)
        }, 1000)
    }

    function layoutContent() {
        var limit = new Date().getTime() - 7 * 3600 * 1000 * 24;
        var current_record = machine.context.checkData ? (machine.context.checkData as any).current_record : null;
        if (current_record && current_record.last_real_check_time)
            limit = current_record.last_real_check_time
        return <View style={{ backgroundColor: '#fff' }}>
            <LimitPickers limit={limit} limitDay={7} onCancel={hidePicker} onChange={(e) => {
                console.log(new Date(e))
                pickerConfirm(e)
                hidePicker()
            }} />
        </View>
    }

    function pickerConfirm(t: number) {
        debugger
        console.log(t)
        var date = new Date(t)
        var setDate = new Date(global.set_time);
        date.setMilliseconds(setDate.getMilliseconds());
        date.setSeconds(setDate.getSeconds());

        t = date.getTime();
        console.log(t);

        if (isFast) {
            if (value == 'WAIT_FOR_START') {
                // const duration = fastValues[0] * 3600 * 1000 + fastValues[1] * 60 * 1000
                startFast(t, fastDuration);
            }
            else {
                endFast(t)
            }
        }
        else {
            if (value == 'WAIT_FOR_START' || value == 'ONGOING1') {
                // const duration = sleepValues[0] * 3600 * 1000 + sleepValues[1] * 60 * 1000
                startSleep(t, sleepDuration);
            }
            else {
                endSleep(t)
            }
        }
    }

    function mixedBtns() {
        return <View>
            {
                (value == 'WAIT_FOR_START' || value == 'DONE') &&
                <Text style={{ color: '#AAFF00' }} onClick={showPicker}>Start Fast</Text>
            }
            {
                (value == 'ONGOING'/* ||value == 'ONGOING1' || value == 'ONGOING2'*/ || value == 'ONGOING3') &&
                <Text style={{ color: '#AAFF00' }} onClick={showPicker}>End Fast</Text>
            }
            {
                value == 'ONGOING1' && <Text style={{ color: '#00ffff' }} onClick={showPicker}>Start Sleep</Text>
            }
            {
                value == 'ONGOING2' && <Text style={{ color: '#00ffff' }} onClick={showPicker}>End Sleep</Text>

            }
        </View>
    }

    function fastBtns() {
        return <View>
            <Text style={{ color: '#AAFF00' }} onClick={showPicker}>{value == 'ONGOING' ? 'End Fast' : 'Start Fast'}</Text>
        </View>
    }

    function sleepBtns() {
        return <View>
            {
                value == 'ONGOING' ? <Text style={{ color: '#00ffff' }} onClick={showPicker}>End Sleep</Text> :
                    <Text style={{ color: '#00ffff' }} onClick={showPicker}>Start Sleep</Text>
            }
        </View>
    }

    const handlePickerChange = (e: string) => {
        var [hour, minute] = e.split(':').map(x => parseInt(x))
        isFast ? setFastValues([hour, minute]) : setSleepValues([hour, minute]);
    };

    function durationChange(e) {
        var count = (e[0] + common.duration.min) * 60 + e[1] * common.duration.step
        isFast ? setFastDuration(count * 60000) : setSleepDuration(count * 60000);
        isFast ? setFastPickerValue(e) : setSleepPickerValue(e)

        setIsOpenDurationPicker(false)
    }

    function login() {
        Taro.navigateTo({
            url: '/pages/ChooseAuth'
        })
    }

    function durationFormate() {
        if (isFast) {
            var t = fastDuration / 60000
            var hour = Math.floor(t / 60)
            var minute = Math.floor(t % 60)
            return `${hour > 0 ? hour + '小时' : ''}${minute > 0 ? minute + '分钟' : ''}`
        }
        else {
            var t = sleepDuration / 60000
            var hour = Math.floor(t / 60)
            var minute = Math.floor(t % 60)
            return `${hour > 0 ? hour + '小时' : ''}${minute > 0 ? minute + '分钟' : ''}`
        }

    }

    function showDurationPicker() {
        setIsOpenDurationPicker(true)
    }

    if (!user.isLogin) {
        return <View style={{ display: 'flex', flexDirection: 'column', width: '100%', alignItems: 'center' }}>
            <Text>16:00</Text>
            {/* <PickerViews onChange={() => { }} items={[pickerDurations()]} value={[12 * 15]} /> */}
            {/* <TimePickers time={isFast ? fastStr : sleepStr} content="" change={handlePickerChange} isPickerView={true} /> */}
            <Text style={{ color: '#AAFF00' }} onClick={login}>Start Fast</Text>
        </View>
    }


    function durationPickerContent() {
        return <View style={{ color: '#000', backgroundColor: '#fff' }}>
            <PickerViews onChange={durationChange} items={durationDatas(common)} value={isFast ? fastPickerValue : sleepPickerValue} height={200} showBtns={true} onCancel={() => { setIsOpenDurationPicker(false) }} />
        </View>
    }

    function minus() {
        if (isFast) {
            var count = fastDuration - 5 * 60 * 1000
            setFastDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setFastPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
        else {
            var count = sleepDuration - 5 * 60 * 1000

            setSleepDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setSleepPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
    }

    function plus() {
        if (isFast) {
            var count = fastDuration + 5 * 60 * 1000
            setFastDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setFastPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
        else {
            var count = sleepDuration + 5 * 60 * 1000

            setSleepDuration(count)
            var hour = count / 60000 / 60
            var minute = count / 60000 % 60

            setSleepPickerValue(durationIndex('00:00', `${hour > 10 ? hour : '0' + hour}:${minute > 10 ? minute : '0' + minute}`, common))
        }
    }

    function disableMinus() {
        if (isFast) {
            if (fastDuration <= 60 * 60 * 1000) {
                return true;
            }
        }
        else {
            if (sleepDuration <= 60 * 60 * 1000) {
                return true;
            }
        }
        return false;
    }

    function disablePlus() {
        if (isFast) {
            if (fastDuration >= 23 * 60 * 60 * 1000) {
                return true;
            }
        }
        else {
            if (sleepDuration >= 23 * 60 * 60 * 1000) {
                return true;
            }
        }
        return false;
    }
    return (
        <View style={{ display: 'flex', flexDirection: 'column', width: '100%', alignItems: 'center' }}>
            {
                machine.context.checkData && (machine.context.checkData as any).current_record.last_real_check_time &&
                <Text style={{ width: '100%', textAlign: 'center', color: 'red' }}>
                    {TimeFormatter.formateTime((machine.context.checkData as any).current_record.last_real_check_time)}
                </Text>
            }
            {
                value == 'ONGOING' && <View>
                    <Text>{(machine.context.checkData as any).current_record.scenario == 'FAST' ?
                        TimeFormatter.countdown((machine.context.checkData as any).current_record.fast.target_end_time) :
                        TimeFormatter.countdown((machine.context.checkData as any).current_record.sleep.target_end_time)}</Text>
                </View>
            }
            {
                (value == 'ONGOING1' || value == 'WAIT_FOR_START') && <Stepper style={{ marginBottom: 10 }} child={
                    <Text style={{ width: 150, textAlign: 'center' }} onClick={showDurationPicker}>{durationFormate()}</Text>
                } minus={minus} plus={plus} disableMinus={disableMinus()} disablePlus={disablePlus()} />
                // <Text style={{marginBottom:10}} onClick={showDurationPicker}>时长：{durationFormate()}</Text>
            }
            {
                machine.context.checkData && value == 'ONGOING2' && <View>
                    <Text>{TimeFormatter.countdown((machine.context.checkData as any).current_record.sleep.target_end_time)}</Text>
                </View>
            }

            {
                machine.context.checkData && value == 'ONGOING3' && <View>
                    <Text>{TimeFormatter.countdown((machine.context.checkData as any).current_record.fast.target_end_time)}</Text>
                </View>
            }

            <View>
                {
                    key === 'FAST_SLEEP' && mixedBtns()
                }
                {
                    key === 'FAST' && fastBtns()
                }
                {
                    key === 'SLEEP' && sleepBtns()
                }
            </View>
            {
                showModal && isOpen && <Modal children={layoutContent()} dismiss={() => setIsOpen(false)} />
            }
            {
                isOpenDurationPicker && <Modal children={durationPickerContent()} dismiss={() => setIsOpenDurationPicker(false)} />
            }

            {/* {
                showModal && <AtFloatLayout
                    isOpened={isOpen}
                    onClose={() => {
                        setIsOpen(false)
                        setShowModal(false)
                    }}
                    title="">
                    {
                        layoutContent()
                    }
                </AtFloatLayout>
            }
            <AtFloatLayout
                isOpened={isOpenDurationPicker}
                onClose={() => {
                    setIsOpenDurationPicker(false)
                }}
                title="">
                {
                    durationPickerContent()
                }
            </AtFloatLayout> */}

        </View>
    )
}