import { View, Text } from '@tarojs/components'
import './CircadianDetailPopup.scss'
import { useTranslation } from 'react-i18next'
import { useState } from 'react'
import { rpxToPx } from '@/utils/tools'
import { TimeFormatter } from '@/utils/time_format'
import { useSelector } from 'react-redux'
import { ColorType } from '@/context/themes/color'
import Timeline from '@/components/view/Timeline'

export default function DayNightDetailPopup(props: {
    isNight: boolean,
    authInfo: any,
    sunsetDate: any,
    sunriseDate: any,
    sunriseTmrDate: any,
    sunsetTime: any,
    sunriseTime: any,
    sunriseTmrTime: any,
    nightDate:any,
    dayDate:any,
    onClose: Function
}) {
    const dayNight = useSelector((state: any) => state.night);
    const day = useSelector((state: any) => state.day);
    const [tabIndex, setTabIndex] = useState(0)
    const { t } = useTranslation()

    function getTitle() {
        return props.isNight ? t('feature.day_night.night_popover') : t('feature.day_night.day_popover')
    }

    function nightDuration() {

        var sunRiseObj = dayNight.nightRingSunrise
        var sunSetObj = dayNight.nightRingSunset
        var sunRise = 24 * 60 + parseInt(sunRiseObj.split(':')[0]) * 60 + parseInt(sunRiseObj.split(':')[1])
        var sunSet = parseInt(sunSetObj.split(':')[0]) * 60 + parseInt(sunSetObj.split(':')[1])
        if (sunSetObj.indexOf('PM') != -1) {
            sunSet += 12 * 60
        }

        var duration = (sunRise - sunSet) * 60 * 1000

        return TimeFormatter.calculateTimeDifference(new Date().getTime(), new Date().getTime() + duration);
    }

    function dayDuration() {
        var sunRiseObj = day.dayRingSunrise
        var sunSetObj = day.dayRingSunset
        var sunRise = parseInt(sunRiseObj.split(':')[0]) * 60 + parseInt(sunRiseObj.split(':')[1])
        var sunSet = parseInt(sunSetObj.split(':')[0]) * 60 + parseInt(sunSetObj.split(':')[1])
        if (sunSetObj.indexOf('PM') != -1) {
            sunSet += 12 * 60
        }

        var duration = (sunSet - sunRise) * 60 * 1000

        return TimeFormatter.calculateTimeDifference(new Date().getTime(), new Date().getTime() + duration);
    }

    function showExtraData() {
        var now = new Date()
        if (props.isNight) {
            if (props.sunsetDate.getTime() > now.getTime()) {
                return false
            }
            return true
        }
        if (props.sunriseDate.getTime() < now.getTime() && now.getTime() < props.sunsetDate.getTime()) {
            return true;
        }
        return false
    }

    function timeCount() {
        var now = new Date()
        if (props.isNight) {
            if (now.getTime() < props.sunriseTmrDate.getTime()) {
                return TimeFormatter.countdown(props.sunsetDate.getTime())
            }
            return TimeFormatter.countdown(props.sunsetDate.getTime())
        } else {

            if (now.getTime() < props.sunsetDate.getTime()) {
                return TimeFormatter.countdown(props.sunriseDate.getTime())
            }
            return TimeFormatter.countdown(props.sunriseTmrDate.getTime())


        }
    }

    function timeCount2() {
        var now = new Date()
        if (props.isNight) {

            if (now.getTime() < props.sunsetDate.getTime()) {
                return TimeFormatter.countdown(props.sunriseTmrDate.getTime())
            }
            return TimeFormatter.countdown(props.sunriseTmrDate.getTime())

        } else {
            return TimeFormatter.countdown(props.sunsetDate.getTime())
        }
    }

    function timeDesc() {
        var now = new Date()
        if (props.isNight) {
            var list = props.sunsetTime.split(':')
            var hour = parseInt(list[0])
            var min = parseInt(list[1])
            var second = list.length == 3 ? parseInt(list[2]) : 0
            now.setHours(hour)
            now.setMinutes(min)
            now.setSeconds(second)

            var sunriseDate = new Date()
            var list2 = props.sunriseTmrTime.split(':')
            var hour2 = parseInt(list2[0])
            var min2 = parseInt(list2[1])
            var second2 = list2.length == 3 ? parseInt(list2[2]) : 0
            sunriseDate.setHours(hour2)
            sunriseDate.setMinutes(min2)
            sunriseDate.setSeconds(second2)
            if (sunriseDate.getTime() > new Date().getTime()) {
                return t('feature.day_night.time_past_sunset')//'Time past Sunset'
            }

            if (now.getTime() < new Date().getTime()) {
                return t('feature.day_night.time_past_sunset')//'Time past Sunset'
            }
            return t('feature.day_night.time_to_sunset')//'Time to Sunset'
        }
        else {
            var list = props.sunriseTime.split(':')
            var hour = parseInt(list[0])
            var min = parseInt(list[1])
            var second = list.length == 3 ? parseInt(list[2]) : 0
            now.setHours(hour)
            now.setMinutes(min)
            now.setSeconds(second)

            var sunsetDate = new Date()
            var list2 = props.sunsetTime.split(':')
            var hour2 = parseInt(list2[0])
            var min2 = parseInt(list2[1])
            var second2 = list2.length == 3 ? parseInt(list2[2]) : 0
            sunsetDate.setHours(hour2)
            sunsetDate.setMinutes(min2)
            sunsetDate.setSeconds(second2)

            if (new Date().getTime() > sunsetDate.getTime()) {
                return t('feature.day_night.time_to_sunrise')//'Time to Sunrise'
            }
            if (now.getTime() < new Date().getTime()) {
                return t('feature.day_night.time_past_sunrise')//'Time past Sunrise'
            }
            return t('feature.day_night.time_to_sunrise')//'Time to Sunrise'
        }
    }

    function timeDesc2() {
        if (props.isNight) {
            return t('feature.day_night.time_to_sunrise')//'Time to Sunrise'
        }
        return t('feature.day_night.time_to_sunset')//'Time to Sunset'
    }

    function overview() {
        return <View className='pop_ring_bg pop_overview_bg'>
            <Text className='pop_duration_title'>{props.isNight ? t('feature.day_night.night_duration') : t('feature.day_night.day_duration')}</Text>
            <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: rpxToPx(8), display: 'flex', width: '100%' }}>
                <Text className='pop_duration_txt'>{props.isNight ? nightDuration() : dayDuration()}</Text>
            </View>
            <View style={{ marginTop: rpxToPx(20), display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                <View className='countdown_time_bg'>
                    <Text className='title'>{timeDesc()}</Text>
                    <Text className='value' style={{ color: props.isNight ? ColorType.night : ColorType.day }}>{timeCount()}</Text>
                </View>
                {
                    showExtraData() && <View className='countdown_time_bg'>
                        <Text className='title'>{timeDesc2()}</Text>
                        <Text className='value' style={{ opacity: 0.4, color: props.isNight ? ColorType.night : ColorType.day }}>{timeCount2()}</Text>
                    </View>
                }

            </View>
        </View>
    }

    function nightDurationDesc() {
        if (!props.authInfo || !(props.authInfo as any).lat) {
            if (new Date().getHours() >= 6) {
                return [t('feature.day_night.tonight'),t('feature.day_night.tomorrow_morning')]
            }
            return [t('feature.day_night.last_night'),t('feature.day_night.this_morning')]
            // return `Yesterday ${sunsetTime} - Today ${sunriseTmrTime}`
        }
        if (props.nightDate.getDate() == new Date().getDate()) {
            return [t('feature.day_night.tonight'),t('feature.day_night.tomorrow_morning')]
        }
        return [t('feature.day_night.last_night'),t('feature.day_night.this_morning')]
        //`Yesterday ${sunsetTime} - Today ${sunriseTmrTime}`
    }

    function dayDurationDesc() {
        if (!props.authInfo || !(props.authInfo as any).lat) {
            if (new Date().getHours() >= 18) {
                return `${t('feature.day_night.tomorrow')}`

                // return `Tomorrow ${sunriseTime} - ${sunsetTime}`
            }
            return `${t('feature.day_night.today')}`
            // return `Today ${sunriseTime} - ${sunsetTime}`
        }
        if (props.dayDate.getDate() == new Date().getDate()) {
            return `${t('feature.day_night.today')}`
            // return `Today ${sunriseTime} - ${sunsetTime}`
        }
        return `${t('feature.day_night.tomorrow')}`
        // return `Tomorrow ${sunriseTime} - ${sunsetTime}`
    }

    function events() {
        let timelineItems: any = []
        
        if (props.isNight) {
            var list = nightDurationDesc()
            timelineItems.push(
                {
                    status: showExtraData() ? 'done' : 'padding',
                    title: '日落',//list[0],
                    content: list[0]+' '+props.sunsetTime,
                    date: '',
                    color: ColorType.night
                }
            )

            timelineItems.push(
                {
                    status: 'padding',
                    title: '日出',//list[1],
                    content: list[1]+' '+props.sunriseTmrTime,
                    date: '',
                    color: ColorType.night
                }
            )
        }
        else {
            timelineItems.push(
                {
                    status: showExtraData() ? 'done' : 'padding',
                    title: '日出',//dayDurationDesc(),
                    content: dayDurationDesc()+' '+props.sunriseTime,
                    date: '',
                    color: ColorType.day
                }
            )

            timelineItems.push(
                {
                    status: 'padding',
                    title: '日落',//dayDurationDesc(),
                    content: dayDurationDesc()+' '+props.sunsetTime,
                    date: '',
                    color: ColorType.day
                }
            )
        }
        return <View style={{ display: 'flex', flexDirection: 'row' }}>
            <Timeline items={timelineItems} title='' width={468} />
        </View>
    }

    return <View className='detail_container'>
        <Text className='detail_popup_title'>{getTitle()}</Text>
        <View className='detail_tabbar'>
            <View onClick={() => { setTabIndex(0) }} className={tabIndex == 0 ? 'detail_tabitem_sel' : 'detail_tabitem_nor'}>{t('feature.day_night.overview')}</View>
            <View onClick={() => { setTabIndex(1) }} className={tabIndex == 1 ? 'detail_tabitem_sel' : 'detail_tabitem_nor'}>{t('feature.day_night.events')}</View>
        </View>

        <View className='detail_content'>
            {
                tabIndex == 0 ? overview() : events()
            }
        </View>
        <View className='detail_bottom'>
            <View className='detail_bottom_btn' onClick={(e) => {
                if (process.env.TARO_ENV == 'weapp') {
                    e.stopPropagation()
                }
                props.onClose();
            }}>{t('feature.track_time_duration.common.okay')}</View>
        </View>
    </View>
}