import { View, Text } from "@tarojs/components";
import trackTimeService, { machine } from "@/store/trackTimeMachine"
import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { TimeFormatter } from "@/utils/time_format";
// import "taro-ui/dist/style/components/float-layout.scss";
import { delRecord } from "@/services/trackTimeDuration";
import Modal from "@/components/layout/Modal";
import Rings, { BgRing, CurrentDot, RealRing, RingCommon } from './Rings';
import { getBgRing, getCommon, getDot, getReal, getTarget } from "../hooks/RingData";
import Timeline from "@/components/view/Timeline";


export default function Component(props: { type?: string, data?: any, delSuccess?: Function }) {
    const [checkData, setCheckData] = useState(null)

    const [key, setKey] = useState('');
    const [value, setValue] = useState('');
    const [isOpen, setIsOpen] = useState(false);
    const [isLatest, setIsLatest] = useState(props.type == 'latest');

    const [timerId, setTimerId] = useState(null)
    const [counter, setCounter] = useState(0)

    const canvasId = props.type == 'latest' ? 'latest' : props.type == 'record' ? props.data.id : 'current'

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

    useEffect(() => {
        if (machine.context.checkData) {
            setCheckData(machine.context.checkData as any);
        }
        getStateDetail();
    }, [machine.context.checkData]);
    useEffect(() => {
        trackTimeService.onTransition(state => {
            getStateDetail();
        });
    }, []);


    function getStateDetail() {
        if (props.type == 'latest') {
            if (machine.context.checkData) {
                setKey((machine.context.checkData as any).latest_record.scenario);
                setValue((machine.context.checkData as any).latest_record.status);
            }
            return
        }

        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) {
            setKey('FAST');
            setValue((state as any).FAST);
        }
        if ((state as any).SLEEP) {
            setKey('SLEEP');
            setValue((state as any).SLEEP);
        }

    }

    function editSchedule() {
        Taro.navigateTo({
            url: '/pages/clock/SetSchedule'
        })
    }

    function showStage(e) {
        setIsLatest(false);
        setIsOpen(true)
        debugger
        e.stopPropagation()
    }

    function showLatest(e) {
        // startTimer();
        setIsLatest(true)
        setIsOpen(true)
        debugger
        e.stopPropagation()
    }

    function getTime(t1: number, t2: number) {
        return TimeFormatter.calculateTimeDifference(t1, t2)
    }



    function getStepATime(obj) {
        if (obj.status == 'COMPLETED' && obj.sleep.status == 'NOT_STARTED') {
            return '未知'
        }
        return obj.status == 'ONGOING1' ?
            getTime(obj.fast.real_start_time, (new Date()).getTime()) :
            obj.sleep.real_start_time ? getTime(obj.sleep.real_start_time, obj.fast.real_start_time ? obj.fast.real_start_time : obj.fast.target_start_time) :
                getTime(obj.sleep.target_start_time, obj.fast.real_start_time ? obj.fast.real_start_time : obj.fast.target_start_time)
    }

    function getStepBTime(obj) {
        if (obj.status == 'ONGOING1') return 'Next up'
        if (obj.status == 'ONGOING2') return getTime(obj.sleep.real_start_time, (new Date()).getTime())
        if (obj.status == 'WAIT_FOR_START') return getTime(obj.sleep.target_end_time, obj.sleep.target_start_time)
        if (obj.sleep.status == 'NOT_COMPLETED' || obj.sleep.status == 'NOT_STARTED') return '未知'
        return getTime(obj.sleep.real_end_time, obj.sleep.real_start_time)

    }

    function getStepCTime(obj) {
        if (obj.status == 'ONGOING1') return 'Final stage'
        if (obj.status == 'ONGOING2') return 'Next up'
        if (obj.status == 'ONGOING3') return getTime(obj.sleep.real_end_time, (new Date()).getTime())
        if (obj.status == 'WAIT_FOR_START') return getTime(obj.fast.target_end_time, obj.sleep.target_end_time)
        if (obj.sleep.status == 'NOT_COMPLETED' || obj.sleep.status == 'NOT_STARTED') return '未知'
        return getTime(obj.fast.real_end_time, obj.sleep.real_end_time)
    }

    function layoutContent() {
        debugger
        //当前断食阶段
        var obj = isLatest ? (checkData as any).latest_record : (checkData as any).current_record
        if (props.type == 'record') {
            obj = props.data
        }
        return <View style={{ flexDirection: 'column', display: 'flex', color: '#000', backgroundColor: '#fff', paddingTop: 50, paddingBottom: 50, position: 'relative' }}>
            <Text style={{ position: 'absolute', top: 5, right: 20 }} onClick={() => setIsOpen(false)}>关闭</Text>
            {
                obj.status == 'WAIT_FOR_START' ? <Text>断食阶段目标</Text> :
                    obj.status == 'COMPLETED' ? <Text>断食阶段</Text> :
                        <Text>当前断食阶段</Text>
            }
            <View style={{ flexDirection: 'row', display: 'flex' }}>
                <Text>阶段A</Text>
                <Text style={{ color: obj.status == 'ONGOING1' ? '#AAFF00' : '', marginLeft: 20, marginRight: 20 }}> 睡前断食</Text>
                <Text style={{ color: obj.status == 'ONGOING1' ? '#AAFF00' : '' }}> {
                    getStepATime(obj)
                }</Text>
            </View>
            <View style={{ flexDirection: 'row', display: 'flex' }}>
                <Text>阶段B</Text>
                <Text style={{ color: obj.status == 'ONGOING2' ? '#AAFF00' : '', marginLeft: 20, marginRight: 20 }}> 睡眠中断食</Text>

                <Text style={{ color: obj.status == 'ONGOING2' ? '#AAFF00' : '' }}>
                    {
                        getStepBTime(obj)
                    }
                </Text>
            </View>
            <View style={{ flexDirection: 'row', display: 'flex' }}>
                <Text>阶段C</Text>
                <Text style={{ color: obj.status == 'ONGOING3' ? '#AAFF00' : '', marginLeft: 20, marginRight: 20 }}> 起床后断食</Text>
                <Text style={{ color: obj.status == 'ONGOING3' ? '#AAFF00' : '' }}>
                    {
                        getStepCTime(obj)
                    }
                </Text>
            </View>
        </View>
    }

    //🚫❌⭕️✅
    function statusString(isFast: boolean, isStart: boolean, data: any) {
        if (props.type == 'latest' || props.type == 'record') {
            if (isFast) {
                if (data.fast.status == 'COMPLETED') {
                    return '✅'
                }
            }
            else {
                if (data.sleep.status == 'COMPLETED') {
                    return '✅'
                }
                else if (data.sleep.status == 'NOT_STARTED') {
                    return '🚫'
                }
                else if (data.sleep.status == 'NOT_COMPLETED') {
                    return isStart ? '✅' : '🚫'
                }
            }
        }
        if (value == 'WAIT_FOR_START') {
            return '⭕️'
        }
        else if (value == 'ONGOING') {
            if (isFast && isStart) {
                return '✅'
            }
            else if (!isFast && isStart) {
                return '✅'
            }
        }
        else if (value == 'ONGOING1') {
            if (isFast && isStart) {
                return '✅'
            }
        }
        else if (value == 'ONGOING2') {
            if (isStart) {
                return '✅'
            }
        }
        else if (value == 'ONGOING3') {
            if (isFast && !isStart) {
                return '⭕️'
            }
            else {
                return '✅'
            }
        }

        return '⭕️'
    }

    function getStatus(isFast: boolean, isStart: boolean, data: any) {
        if (props.type == 'latest' || props.type == 'record') {
            if (isFast) {
                if (data.fast.status == 'COMPLETED') {
                    return 'done'
                }
            }
            else {
                if (data.sleep.status == 'COMPLETED') {
                    return 'done'
                }
                else if (data.sleep.status == 'NOT_STARTED') {
                    return 'un_done'
                }
                else if (data.sleep.status == 'NOT_COMPLETED') {
                    return isStart ? 'done' : 'un_done'
                }
            }
        }
        if (value == 'WAIT_FOR_START') {
            return 'padding'
        }
        else if (value == 'ONGOING') {
            if (isFast && isStart) {
                return 'done'
            }
            else if (!isFast && isStart) {
                return 'done'
            }
        }
        else if (value == 'ONGOING1') {
            if (isFast && isStart) {
                return 'done'
            }
        }
        else if (value == 'ONGOING2') {
            if (isStart) {
                return 'done'
            }
        }
        else if (value == 'ONGOING3') {
            if (isFast && !isStart) {
                return 'padding'
            }
            else {
                return 'done'
            }
        }

        return 'padding'
    }

    function scheduleItems(data) {
        if (!data) {
            return <View></View>
        }
        var obj = props.type == 'latest' ? (data as any).latest_record : (data as any).current_record;
        if (props.type == 'record') {
            obj = data//(data as any).latest_record
        }

        var timelineItems: any = [];
        if (obj.fast) {
            timelineItems.push(
                {
                    status: getStatus(true, true, obj),
                    title: '开始断食',
                    content: formateTime(obj.fast, false),
                }
            )
        }
        if (obj.sleep) {
            timelineItems.push(
                {
                    status: getStatus(false, true, obj),
                    title: '开始睡眠',
                    content: formateTime(obj.sleep, false),
                }
            )
        }
        if (obj.sleep) {
            timelineItems.push(
                {
                    status: getStatus(false, false, obj),
                    title: '结束睡眠',
                    content: formateTime(obj.sleep, true),
                }
            )
        }
        if (obj.fast) {
            timelineItems.push(
                {
                    status: getStatus(true, false, obj),
                    title: '结束断食',
                    content: formateTime(obj.fast, true),
                }
            )
        }

        return <Timeline items={timelineItems} />

        // return <View>
        //     {
        //         obj && <View style={{ flexDirection: 'column', display: 'flex' }}>
        //             {obj.fast && <Text>{statusString(true, true, obj)}开始断食：{formateTime(obj.fast, false)}</Text>}
        //             {obj.sleep && <Text>{statusString(false, true, obj)}开始睡眠：{formateTime(obj.sleep, false)}</Text>}
        //             {obj.sleep && <Text>{statusString(false, false, obj)}结束睡眠：{formateTime(obj.sleep, true)}</Text>}
        //             {obj.fast && <Text>{statusString(true, false, obj)}结束断食：{formateTime(obj.fast, true)}</Text>}
        //         </View>
        //     }
        // </View>
    }

    function formateTime(obj: any, isEnd: boolean) {

        if (isEnd) {
            if (obj.real_end_time) {
                return TimeFormatter.formatTimestamp(obj.real_end_time)
            }
            else {
                return TimeFormatter.formatTimestamp(obj.target_end_time)
            }
        }
        else {
            if (obj.real_start_time) {
                return TimeFormatter.formatTimestamp(obj.real_start_time)
            }
            else {
                return TimeFormatter.formatTimestamp(obj.target_start_time)
            }
        }

    }

    function more(e) {
        Taro.showActionSheet({
            itemList: ['删除', '分享']
        })
            .then(res => {
                console.log(res.tapIndex)
                switch (res.tapIndex) {
                    case 0:
                        {
                            del()
                        }
                        break;
                }
            })
            .catch(err => {
                console.log(err.errMsg)
            })
        e.stopPropagation()
    }

    function del() {
        Taro.showModal({
            title: '删除记录',
            content: '确定删除该记录吗？',
            success: res => {
                if (res.confirm) {
                    delRecord(props.data.id
                    ).then(res => {
                        Taro.showToast({
                            title: '删除成功'
                        })
                        props.delSuccess && props.delSuccess(props.data)
                        // Taro.navigateBack()
                    })
                }
            }
        })
    }

    function all() {
        if (props.type == 'latest') {
            Taro.navigateTo({
                url: '/pages/common/RecordsHistory?type=time&title=Time'
            })
        }
    }

    // const common: RingCommon = {
    //     useCase: 'Record',
    //     radius: 50,
    //     lineWidth: 8,
    //     isFast: true,
    //     status: getRecord()?getRecord().status:'WAIT_FOR_START'
    // }

    // const common2: RingCommon = {
    //     useCase: 'Record',
    //     radius: 40,
    //     lineWidth: 8,
    //     isFast: true,
    //     status: getRecord()?getRecord().status:'WAIT_FOR_START'
    // }

    // const bgRing: BgRing = {
    //     color: '#262626'
    // }

    // const realRing: RealRing = {
    //     color: '#AAFF00',
    //     startArc: 0,
    //     durationArc: 0
    // }

    // const realRing2: RealRing = {
    //     color: '#00FFFF',
    //     startArc: 0,
    //     durationArc: 0
    // }

    // const currentDot: CurrentDot = {
    //     color: '#AAFF00',
    //     lineWidth: 8,
    //     borderColor: 'black'
    // }

    // const currentDot2: CurrentDot = {
    //     color: '#00FFFF',
    //     lineWidth: 8,
    //     borderColor: 'black'
    // }

    // function startArc(time: number) {
    //     var date = new Date(time);
    //     var hour = date.getHours();
    //     var minute = date.getMinutes();
    //     var second = date.getSeconds();
    //     return (hour * 3600 + minute * 60 + second) / (24 * 3600) * 2 * Math.PI - Math.PI / 2.0;
    // }

    function durationArc(start_time: number, end_time: number) {
        var duration = (end_time - start_time) / 1000;
        return duration / (24 * 3600) * 2 * Math.PI;
    }

    function getRecord() {
        var detail = props.type == 'record' ? props.data : checkData
        if (detail) {
            var record = detail;
            if (props.type == 'latest') {
                record = detail.latest_record
            }
            else if (props.type != 'record') {
                record = detail.current_record
            }

            return record;
        }
        return
    }



    function bigRing() {
        var record = getRecord()
        if (!record) return null

        var common = getCommon(null, true)
        var bgRing = getBgRing()

        if (props.type == 'record' || props.type == 'latest') {
            var realRing = getReal(record, true, true)
            return <Rings common={common} bgRing={bgRing} canvasId={canvasId} realRing={realRing} />
        }
        else {
            var currentDot1 = getDot(record, true)
            var targetBigRing1 = getTarget(record, true)
            if (record.status == 'ONGOING') {
                var realRing1 = getReal(record, true, false)

                return <Rings common={common} bgRing={bgRing} currentDot={currentDot1} realRing={realRing1} targetRing={targetBigRing1} canvasId={canvasId} />
            }
            if (record.status == 'WAIT_FOR_START') {
                return <Rings common={common} bgRing={bgRing} currentDot={currentDot1} canvasId={canvasId} />
            }
            var realRing1 = getReal(record, true, false)
            return <Rings common={common} bgRing={bgRing} realRing={realRing1} currentDot={currentDot1} targetRing={targetBigRing1} canvasId={canvasId} />
        }
    }

    function smallRing() {
        if (!checkData) return null
        var record = getRecord()
        if (record.scenario == 'FAST_SLEEP') {
            var common = getCommon(null, false)
            var bgRing = getBgRing()
            var realRing = getReal(record, false, false)
            if (props.type == 'record' || props.type == 'latest') {
                if (record.sleep.status == 'WAIT_FOR_END') {
                    realRing.durationArc = durationArc(record.sleep.target_start_time, (new Date()).getTime())
                    return <Rings common={common} bgRing={bgRing} canvasId={canvasId + 'small'} realRing={realRing} />
                }
                else if (record.sleep.status == 'NOT_COMPLETED') {
                    realRing.durationArc = 0.01
                    return <Rings common={common} bgRing={bgRing} canvasId={canvasId + 'small'} realRing={realRing} />
                }
                else if (record.sleep.status == 'COMPLETED') {
                    realRing = getReal(record, false, true)
                    return <Rings common={common} bgRing={bgRing} canvasId={canvasId + 'small'} realRing={realRing} />
                }
                return <Rings common={common} bgRing={bgRing} canvasId={canvasId + 'small'} />
            }
            else {


                var currentDot = getDot(record, false)
                var targetRing = getTarget(record, false)
                if (record.status == 'ONGOING2') {
                    var realRing = getReal(record, false, false)
                    return <Rings common={common} bgRing={bgRing} realRing={realRing} currentDot={currentDot} targetRing={targetRing} canvasId={canvasId + 'small'} />
                }
                if (record.status == 'ONGOING3') {
                    currentDot.color = 'rgba(0, 255, 255, 0.5)'
                }
                return <Rings common={common} bgRing={bgRing} currentDot={currentDot} canvasId={canvasId + 'small'} />
            }
            // if (record.sleep.status == 'WAIT_FOR_END') {
            //     realRing2.startArc = startArc(record.sleep.target_start_time)
            //     realRing2.durationArc = durationArc(record.sleep.target_start_time, (new Date()).getTime())
            //     return <Rings common={common2} bgRing={bgRing} canvasId={canvasId + 'small'} realRing={realRing2} />
            // }
            // else if (record.sleep.status == 'NOT_COMPLETED') {
            //     realRing2.startArc = startArc(record.sleep.target_start_time)
            //     realRing2.durationArc = 0.01
            //     return <Rings common={common2} bgRing={bgRing} canvasId={canvasId + 'small'} realRing={realRing2} />
            // }
            // else if (record.status == 'WAIT_FOR_START') {
            //     common2.useCase = 'Clock'
            //     return <Rings common={common2} bgRing={bgRing} currentDot={currentDot2} canvasId={canvasId + 'small'} />
            // }

            // return <Rings common={common2} bgRing={bgRing} canvasId={canvasId + 'small'} />
        }
        return null
    }

    return <View style={{ flexDirection: 'column', display: 'flex', alignItems: 'center', position: 'relative' }} onClick={all}>
        {
            (props.type == 'latest' || props.type == 'record') &&
            <View style={{ position: 'relative', zIndex: 1 }}>
                {
                    bigRing()
                }
                <View style={{ display: 'flex', position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' }}>
                    {
                        smallRing()
                    }
                </View>
            </View>
        }

        {
            props.type == 'latest' ? <Text style={{ color: 'red' }}>Latest</Text> :
                <Text>{value == 'WAIT_FOR_START' ? 'Schedule' : 'Log in Progress'}</Text>
        }
        {
            scheduleItems(props.type == 'record' ? props.data : checkData)
        }

        {
            (props.type != 'record' && value == 'WAIT_FOR_START') && <Text onClick={editSchedule}>调整日程</Text>
        }
        {
            ((props.type == 'record' && props.data.scenario == 'FAST_SLEEP') || (props.type == 'latest' && key == 'FAST_SLEEP')) && <Text onClick={showLatest}>Durations by stage</Text>
        }
        {
            props.type != 'record' && props.type != 'latest' && key == 'FAST_SLEEP' && (value == 'WAIT_FOR_START' ? <Text onClick={showStage}>Duration goals by stage</Text> : <Text onClick={showStage}>Current stage</Text>)
        }
        {
            key == 'FAST_SLEEP' && isOpen && props.type != 'record' && checkData && <Modal children={layoutContent()} dismiss={() => setIsOpen(false)} confirm={() => { }} />
        }
        {
            key == 'FAST_SLEEP' && isOpen && props.type == 'record' && props.data.scenario == 'FAST_SLEEP' && <Modal children={layoutContent()} dismiss={() => setIsOpen(false)} confirm={() => { }} />
        }

        {/* {
            key == 'FAST_SLEEP' && <AtFloatLayout
                isOpened={isOpen}
                onClose={() => {
                    // stopTimer()
                    setIsOpen(false)
                }}
                title="这是个标题">
                {
                    props.type != 'record'&&checkData && layoutContent()
                }
                {
                    props.type == 'record' && props.data.scenario=='FAST_SLEEP' && layoutContent()
                }


            </AtFloatLayout>
        } */}

        {
            props.type == 'record' && <Text style={{ position: 'absolute', right: 20, top: 20 }} onClick={more}>More</Text>
        }
        <Text style={{ opacity: 0 }}>{counter}</Text>

    </View >
}