import { useEffect, useState } from 'react'
import './DayLight.scss'
import { View, Text, Switch, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useDispatch, useSelector } from 'react-redux'
import { updateMember } from '@/store/day_night'
export default function DayLight() {
    const [showRing, setShowRing] = useState(false)
    const [isTomorrow, setIsTomorrow] = useState(false)
    const [isMember, setIsMember] = useState(false)
    const [isNight, setIsNight] = useState(false)
    const [authInfo, setAuthInfo] = useState(null)
    const [sunriseTime, setSunriseTime] = useState('06:00')
    const [sunsetTime, setSunsetTime] = useState('18:00')
    const dayNight = useSelector((state: any) => state.dayNight);
    const user = useSelector((state: any) => state.user);
    const dispatch = useDispatch();

    useEffect(() => { getContent() }, [])

    useEffect(() => {
        setIsMember(user.test_user)
        dispatch(updateMember({ isMember: user.test_user,authInfo }))
        if (user.test_user && authInfo) {
            setSunriseTime('07:00')
            setSunsetTime('19:00')
        }
        else {
            setSunriseTime('06:00')
            setSunsetTime('18:00')
        }
    }, [user.test_user,authInfo])

    async function getStorage(key: string) {
        try {
            const res = await Taro.getStorage({ key });
            return res.data;
        } catch {
            return '';
        }
    }

    async function getContent() {
        const isShow = await getStorage('showLightRing') || false
        setShowRing(isShow)

        global.showNightRing = isShow
        global.refreshIndex()

        const gpsInfo = await getStorage('gps') || null
        if (gpsInfo) {
            setAuthInfo(JSON.parse(gpsInfo))
            dispatch(updateMember({ isMember: user.test_user, gpsInfo: JSON.parse(gpsInfo) }))
        }
        else {
            setAuthInfo(null)
        }


        checkData()
    }


    function checkData() {
        var date = new Date()
        var minutes = date.getHours() * 60 + date.getMinutes()
        var riseMinutes = parseInt(sunriseTime.split(':')[0]) * 60 + parseInt(sunriseTime.split(':')[1])
        var setMinutes = parseInt(sunsetTime.split(':')[0]) * 60 + parseInt(sunsetTime.split(':')[1])
        if (minutes >= riseMinutes && minutes < setMinutes) {
            setIsNight(false)
        }
        else {
            setIsNight(true)
        }
        if (minutes >= setMinutes) {
            setIsTomorrow(true)
        }
        else {
            setIsTomorrow(false)
        }
    }

    function buy() {
        Taro.navigateTo({
            url: '/pages/account/Member'
        })
    }

    function auth() {
        Taro.chooseLocation({
            success: function (res) {
                console.log(res)
                setAuthInfo(res as any)
                Taro.setStorage({
                    key: 'gps',
                    data: JSON.stringify(res as any)
                })
                dispatch(updateMember({ isMember: user.test_user, gpsInfo: (res as any) }))
            },
            fail(res) {
                Taro.showToast({
                    title: '位置修改失败!\n请重新选择就近位置',
                    icon: 'none'
                })
            },
        })

    }

    var split = new Date().toString().split(' ');
    var timezone = split[split.length - 2];



    return <View>
        <View className='daylight_row'>
            <Text>Night ring</Text>
            <Switch checked={showRing}
                onChange={(e) => {
                    setShowRing(e.detail.value)
                    global.showNightRing = e.detail.value
                    global.refreshIndex()
                    Taro.setStorage({
                        key: 'showLightRing',
                        data: e.detail.value
                    })
                }}
            />
        </View>
        {
            showRing && <View>
                <View className="daylight_row">
                    <Text>Sunset today</Text>
                    <Text>{sunsetTime}</Text>
                </View>
                <View className="daylight_row">
                    <Text>{isTomorrow ? 'Sunrise tomororow' : 'Sunrise today'}</Text>
                    <Text>{sunriseTime}</Text>
                </View>
                <Text className='daylight_note'>{isMember ? 'Calculated based on your location.' : 'Sunset and sunrise times are global average. For actual times at your location, join our Pro program.'}</Text>
                {
                    isMember ? <View>
                        <View className='daylight_item' onClick={auth}>
                            <Text style={{ flex: 1 }}>Location</Text>
                            {
                                authInfo ? <Text className='address'>{(authInfo as any).address}</Text> :
                                    <Text>Enter</Text>
                            }
                            <Image className="daylight_arrow" src={require('@/assets/images/arrow3.png')} />
                        </View>

                        {
                            authInfo && <View className='daylight_item' >
                                <Text style={{ flex: 1 }}>Latitude</Text>

                                <Text>{(authInfo as any).latitude}</Text>


                            </View>
                        }
                        {
                            authInfo && <View className='daylight_item'>
                                <Text style={{ flex: 1 }}>Longitude</Text>

                                <Text>{(authInfo as any).longitude}</Text>

                            </View>
                        }
                        {
                            authInfo && <View className='daylight_item'>
                                <Text style={{ flex: 1 }}>Time zone</Text>

                                <Text>{timezone}</Text>

                            </View>
                        }

                    </View> :
                        <View className='become_vip' onClick={buy}>
                            <Text style={{ color: '#000' }}>Become Pro</Text>
                        </View>
                }

            </View>
        }

    </View>

}