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 { AtFloatLayout } from "taro-ui";
import LimitPickers from '@/components/LimitPickers';
import { endFast, endSleep, startFast, startSleep } from "../actions/TrackTimeActions";
import { pickerDurations } from "../hooks/Console";
import PickerViews from "@/components/PickerViews";

export default function Component() {
    const [key, setKey] = useState('');
    const [value, setValue] = useState('');
    const user = useSelector((state: any) => state.user);

    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 [resetPicker, setResetPicker] = useState(false);
    const [fastPickerValue, setFastPickerValue] = useState([0])
    const [sleepPickerValue, setSleepPickerValue] = useState([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([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([sleepCount / 60000 / 5 - 12])
            }
        }
    }


    function showPicker() {
        setIsOpen(true)
    }

    function hidePicker() {
        setIsOpen(false)
        setTimeout(() => {
            setResetPicker(true)
        }, 500)
        setTimeout(() => {
            setResetPicker(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
        if (resetPicker) {
            return <View />
        }
        return <View>
            <LimitPickers limit={limit} onCancel={() => { setIsOpen(false) }} onChange={(e) => {
                console.log(new Date(e))
                pickerConfirm(e)
                hidePicker()
            }} />
        </View>
    }

    function pickerConfirm(t: number) {
        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] * 5 + 60;
        isFast ? setFastDuration(count * 60000) : setSleepDuration(count * 60000);
        isFast ? setFastPickerValue(e[0]) : setSleepPickerValue(e[0]);
    }

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

    if (!user.isLogin) {
        return <View style={{ display: 'flex', flexDirection: 'column', width: '100%', alignItems: 'center' }}>
            <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>
    }
    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') &&
                <PickerViews onChange={durationChange} items={[pickerDurations()]} value={isFast ? [fastPickerValue] : [sleepPickerValue]} />
                // <TimePickers time={isFast ? fastStr : sleepStr} content="" change={handlePickerChange} isPickerView={true} />
            }
            {
                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>

            
            <AtFloatLayout
                isOpened={isOpen}
                onClose={() => {
                    setIsOpen(false)
                }}
                title="">
                {
                    layoutContent()
                }
            </AtFloatLayout>
        </View>
    )
}