import { View, Text } from "@tarojs/components";
import Buttons from '@/components/basic/Buttons';
import Texts from '@/components/basic/Texts';
import Rings from '@components/view/Rings';
import Rings2, { BgRing, RingCommon, TargetRing } from './Rings.weapp';
import Footer from '@/components/layout/Footer';
import SingleSelect from '../../../components/input/SingleSelect';
import { ComponentStatus, NaviBarTitleShowType, TemplateType, TextType } from "@utils/types";
import { useTranslation } from 'react-i18next'

import './ChooseScenario.scss'
import { useState } from "react";
import { useDidShow, useReady } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { useDispatch, useSelector } from "react-redux";
import { setScenario, setScenarioName, setStep } from "@/store/scenario";
import { getPlans } from "@/services/trackTimeDuration";
import { ChooseScenarioBtn } from "@/features/common/SpecBtns";
import Layout from "@/components/layout/layout";
import { ColorType } from "@/context/themes/color";
import TitleView from "./TitleView";
import { jumpPage } from "../hooks/Common";


export default function Component() {
    const isFastFirst = true;
    const { t } = useTranslation()
    const dispatch = useDispatch();
    const [selIndex, setSelIndex] = useState(-1)
    const [scenarios, setScenarios] = useState<any[]>([])
    const selScenario = useSelector((state: any) => state.scenario);
    const [count, setCount] = useState(0)

    useDidShow(() => {
        setCount(count + 1)
    })

    useReady(() => {
        if (selScenario) {
            if (selScenario.name == 'FAST_SLEEP') {
                dispatch(setStep(isFastFirst ? 'fast' : 'sleep'))
                setSelIndex(2)
            }
            else if (selScenario.name == 'SLEEP') {
                dispatch(setStep('sleep'))
                setSelIndex(1)
            }
            else {
                dispatch(setStep('fast'))
                setSelIndex(0)
            }
        }
        Taro.getStorage({ key: 'scenarios' }).then(res => {
            if (res) {
                setScenarios(JSON.parse(res.data as any))
            }
        })
        getPlans().then(res => {
            const data = res as { scenarios: any[] };
            Taro.setStorage({ key: 'scenarios', data: JSON.stringify(data.scenarios as any) })
            setScenarios(data.scenarios)
        })
    })

    function next() {
        switch (selIndex) {
            case 0:
                {
                    dispatch(setStep('fast'))
                }
                break;
            case 1:
                {
                    dispatch(setStep('sleep'))
                }
                break;

            case 2:
                {
                    dispatch(setStep(isFastFirst ? 'fast' : 'sleep'))
                }
        }
        jumpPage('/pages/clock/SetSchedule')
    }

    function footerContent() {
        var style = {}
        var background;
        switch (selIndex) {
            case 0:
                style = { backgroundColor: global.fastColor ? global.fastColor : ColorType.fast }
                background = global.fastColor ? global.fastColor : ColorType.fast
                break;
            case 1:
                style = { backgroundColor: global.sleepColor ? global.sleepColor : ColorType.sleep }
                background = global.sleepColor ? global.sleepColor : ColorType.sleep
                break;
            case 2:
                style = {
                    background: 'linear-gradient(to right, ' + (global.fastColor ? global.fastColor : ColorType.fast) + ', ' + (global.sleepColor ? global.sleepColor : ColorType.sleep) + ')'
                }
                background = 'linear-gradient(to right, ' + (global.fastColor ? global.fastColor : ColorType.fast) + ', ' + (global.sleepColor ? global.sleepColor : ColorType.sleep) + ')'
                break;
        }
        console.log(background)
        return <View>
            <ChooseScenarioBtn title={t('feature.common.btn_next')} onClick={next} background={background} />
            {/* <Buttons title='Next' onClick={next} btnStyle={{ ...style, width: 320 }} /> */}
        </View>
    }

    function timeToArc(time: string) {
        var count: number = parseInt(time.split(':')[1]) + parseInt(time.split(':')[0]) * 60
        // count = count>720?count-720:count
        return (count as any) / 1440 * 2 * Math.PI - Math.PI / 2
    }

    function durationToArc(startTime: string, endTime: string) {
        var start: number = parseInt(startTime.split(':')[1]) + parseInt(startTime.split(':')[0]) * 60
        var end: number = parseInt(endTime.split(':')[1]) + parseInt(endTime.split(':')[0]) * 60
        if (end <= start) {
            end += 1440
        }

        return (end - start) / 1440 * 2 * Math.PI
    }

    // function getScheduleTarget(isFast: boolean) {
    //     for (var i = 0; i < scenarios.length; i++) {
    //         if (isFast && scenarios[i].name == 'FAST') {
    //             if (global.schedule_fast){
    //                 return global.schedule_fast
    //             }
    //             return scenarios[i].schedule.fast
    //         }
    //         else if (!isFast && scenarios[i].name == 'SLEEP') {
    //             if (global.schedule_sleep){
    //                 return global.schedule_sleep
    //             }
    //             return scenarios[i].schedule.sleep
    //         }
    //         else {
    //             if (isFast){
    //                 if (global.schedule_fast){
    //                     return global.schedule_fast
    //                 }
    //                 return scenarios[i].schedule.fast
    //             }
    //             if (global.schedule_sleep){
    //                 return global.schedule_sleep
    //             }
    //             return scenarios[i].schedule.sleep
    //         }

    //     }

    // }

    function getScheduleTarget(isFast: boolean) {
        for (var i = 0; i < scenarios.length; i++) {
            if (isFast && scenarios[i].name == 'FAST') {
                if (global.schedule_fast) {
                    return global.schedule_fast
                }
                return scenarios[i].schedule.fast
            }
            else if (!isFast && scenarios[i].name == 'SLEEP') {
                if (global.schedule_sleep) {
                    return global.schedule_sleep
                }
                return scenarios[i].schedule.sleep
            }
        }

    }

    function items() {
        const array: any[] = []
        const common: RingCommon = {
            useCase: 'ChooseScenario',
            radius: 33,
            lineWidth: 8,
            isFast: true,
            status: 'WAIT_FOR_START'
        }
        const common2: RingCommon = {
            useCase: 'ChooseScenario',
            radius: 23,
            lineWidth: 6,
            isFast: true,
            status: 'WAIT_FOR_START'
        }

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

        const targetRing: TargetRing = {
            color: global.fastColor ? global.fastColor : ColorType.fast,
            startArc: timeToArc((getScheduleTarget(true) as any).start_time),
            durationArc: durationToArc((getScheduleTarget(true) as any).start_time, (getScheduleTarget(true) as any).end_time)
        }

        const targetRing2: TargetRing = {
            color: global.sleepColor ? global.sleepColor : ColorType.sleep,
            startArc: timeToArc((getScheduleTarget(false) as any).start_time),
            durationArc: durationToArc((getScheduleTarget(false) as any).start_time, (getScheduleTarget(false) as any).end_time)
        }


        array.push(
            <View className="item_row" style={{ opacity: scenarios.length > 0 ? 1 : 0 }}>
                <Rings2 common={common} bgRing={bgRing} targetRing={targetRing} canvasId='0' />
                <View className="item_txt_bg">
                    <Text className="item_txt" style={{ color: global.fastColor ? global.fastColor : ColorType.fast }}>{t('feature.track_time_duration.choose_scenario.list.item1.name')}</Text>
                    {
                        scenarios[0].count > 0 && <View className="scenario_count">
                            <View className="badge_view1" style={{ backgroundColor: global.fastColor ? global.fastColor : ColorType.fast }}>
                                <Text className="badge1">x{scenarios[0].count}</Text>
                            </View>

                        </View>
                    }
                </View>
            </View>
        );
        array.push(
            <View className="item_row" style={{ opacity: scenarios.length > 0 ? 1 : 0 }}>
                <Rings2 common={common} bgRing={bgRing} targetRing={targetRing2} canvasId='1' />
                <View className="item_txt_bg">
                    <Text className="item_txt" style={{ color: global.sleepColor ? global.sleepColor : ColorType.sleep }}>{t('feature.track_time_duration.choose_scenario.list.item2.name')}</Text>
                    {
                        scenarios[1].count > 0 && <View className="scenario_count">
                            <View className="badge_view1" style={{ backgroundColor: global.sleepColor ? global.sleepColor : ColorType.sleep }}>
                                <Text className="badge1">x{scenarios[1].count}</Text>
                            </View>

                        </View>
                    }
                </View>
            </View>
        )
        array.push(
            <View className="item_row" style={{ opacity: scenarios.length > 0 ? 1 : 0 }}>
                <View style={{ position: 'relative', zIndex: 1 }}>
                    <Rings2 common={common} bgRing={bgRing} targetRing={targetRing} canvasId='3' />
                    <View style={{ display: 'flex', position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' }}>
                        <Rings2 common={common2} bgRing={bgRing} targetRing={targetRing2} canvasId='4' />
                    </View>
                </View>
                <View className="item_txt_bg">
                    <Text className="item_txt fast_sleep_text" >{t('feature.track_time_duration.choose_scenario.list.item3.name')}</Text>
                    {
                        scenarios[2].count > 0 && <View className="scenario_count">
                            <View className="badge_view1" style={{
                                background: 'linear-gradient(to right, ' +
                                    (global.fastColor ? global.fastColor : ColorType.fast) + ', '
                                    + (global.sleepColor ? global.sleepColor : ColorType.sleep) + ')'
                            }}>
                                <Text className="badge1">x{scenarios[2].count}</Text>
                            </View>

                        </View>
                    }
                </View>
            </View>
        )
        return array;
    }

    function handleItemSelect(index: number) {
        setSelIndex(index)
        dispatch(setScenario(scenarios[index]) as any)
        if (index == 0) {
            dispatch(setStep('fast'))
        }
        else if (index == 1) {
            dispatch(setStep('sleep'))
        }
        else {
            dispatch(setStep(isFastFirst ? 'fast' : 'sleep'))
        }
        // dispatch(setScenarioName(scenarios[index].scenario) as any)
    }

    return <Layout title={t('page.choose_scenario.title')}
        titleShowStyle={NaviBarTitleShowType.scrollToShow} type={TemplateType.customHeader}>
        <View className="container">
            <TitleView title={t('page.choose_scenario.title')}
                subTitle={t('page.choose_scenario.sub_title')}
            />
            {/* <Texts text={t('page.choose_scenario.title')} type={TextType.primary}></Texts> */}
            {/* <Texts text={t('page.choose_scenario.sub_title')} type={TextType.secondary}></Texts> */}
            {/* <View style={{ height: 20 }} /> */}
            {
                scenarios.length > 0 && <View style={{ position: 'relative', zIndex: 1 }}>
                    <SingleSelect items={items()} itemSelect={handleItemSelect} selIndex={selIndex} />
                </View>
            }


            <Footer children={footerContent()} />
        </View>
    </Layout>
}