import { View, Text, Image } from "@tarojs/components";
import './index_time.scss';
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { getCommon, getDot } from "@/features/trackTimeDuration/hooks/RingData";
import Rings, { RingCommon, BgRing,TargetRing, CurrentDot } from "@/features/trackTimeDuration/components/Rings";
import { useEffect, useState } from "react";
import DeviceInfo from 'react-native-device-info';
import dayjs from "dayjs";
import moment from 'moment-timezone'
import Modal from "@/components/layout/Modal.weapp";
import { loginAnonymous, place } from "./services/net";
import Taro from "@tarojs/taro";
import { useTranslation } from "react-i18next";
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';



let LinearGradient, useActionSheet, useNavigation
if (process.env.TARO_ENV == 'rn') {
    LinearGradient = require('react-native-linear-gradient').default
    useActionSheet = require('@expo/react-native-action-sheet').useActionSheet
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function IndexTimePage() {
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    const [count, setCount] = useState(0)
    const [showLanguage, setShowLanguage] = useState(false)
    const [isEn, setIsEn] = useState(true)
    const [showDst, setShowDst] = useState(false)
    const [current, setCurrent] = useState<any>(null)
    const { t, i18n } = useTranslation()


    useEffect(() => {
        getLanguage();
        login()
        setInterval(() => {
            setCount(t => t + 1)
        }, 1000)
    }, [])

    async function getLanguage() {
        var language = await getStorage('language') || 'en'
        global.language = language;
        i18n.changeLanguage(language)
        setIsEn(language == 'en')
        dayjs.locale(language == 'en' ? 'en' : 'zh-cn');
        moment.locale(language == 'en' ? 'en' : 'zh-cn');
    }

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

    function changeLanguage(isEnglish: boolean) {
        global.language = isEnglish ? 'en' : 'zh';
        i18n.changeLanguage(isEnglish ? 'en' : 'zh')
        setIsEn(isEnglish)
        Taro.setStorage({ key: 'language', data: isEnglish ? 'en' : 'zh' })
        setShowLanguage(false)
        dayjs.locale(isEnglish ? 'en' : 'zh-cn');
        moment.locale(isEnglish ? 'en' : 'zh-cn');

        if (current) {
            chooseLocation({
                lat: current.geo.lat,
                lng: current.geo.lng
            })
        }
    }

    function login() {
        loginAnonymous(DeviceInfo.getDeviceSync()).then(res => {
            console.log('login success', res)
        }).catch(e => {
            console.log('login error', e)
        })
    }

    function goMap() {
        jumpPage('', 'map', navigation, { source: 'time_of_day', chooseLocation: chooseLocation })
    }

    function chooseLocation(res: any) {
        place(res.lat, res.lng).then(res => {
            console.log(res)
            setCurrent((res as any).location)
            saveLocation((res as any).location)
        }).catch(e => {
            console.log(e)
        })
    }

    function saveLocation(location: any) {

    }

    function getLocation() {
        if (current.geo) {
            if (current.geo.city) {
                return current.geo.city
            }
            if (current.geo.country) {
                return current.geo.country
            }
        }
        return t('time_of_day.index.unknown')
    }

    function getTimezone() {
        if (current.time && current.time.timezone) {
            return current.time.timezone.abbrev + ' · ' + current.time.timezone.name
        }
        return ''
    }

    const common: RingCommon = {
        useCase: 'ChooseScenario',
        radius: 115,
        lineWidth: 26,
        isFast: true,
        status: 'WAIT_FOR_START'
    }

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

    function getArc(){
        var hour = new Date().getHours()
        var minute = new Date().getMinutes()
        var second = new Date().getSeconds()
        if (current) {
            var strHour = moment().tz(current.time.timezone.id).format('H')
            hour = parseInt(strHour)
            var strMin = moment().tz(current.time.timezone.id).format('m')
            minute = parseInt(strMin)
            var strSecond = moment().tz(current.time.timezone.id).format('s')
            second = parseInt(strSecond)
        }

        return (hour*3600+minute*60+second)/(24*3600)*2*Math.PI
    }

    function ring() {
        const currentDot: CurrentDot = {
            color: '#CACACA',
            lineWidth: 10,
            borderColor: '#ffffff',
            offset: 0
        }
        const targetRing: TargetRing = {
            color: '#CACACA',
            startArc: -Math.PI/2,
            durationArc: getArc()
        }

        return <Rings common={common} bgRing={bgRing} targetRing={targetRing}  currentDot={currentDot} canvasId={'smal11l'} />
    }

    function languageModalContent() {
        return <View className="modal_bg">
            <View className="language_content">
                <View className="language_item" onClick={() => changeLanguage(true)}>
                    <Text className="language_text">English</Text>
                    {
                        isEn && <Image className="check" src={require('@assets/index_time/check.png')} />
                    }

                </View>
                <View className="line" />
                <View className="language_item" onClick={() => changeLanguage(false)}>
                    <Text className="language_text">中文</Text>
                    {
                        !isEn && <Image className="check" src={require('@assets/index_time/check.png')} />
                    }
                </View>
            </View>
        </View>
    }

    function formatTime(format: string, timestamp?: number) {
        // var moment = require('moment-timezone');
        if (current) {
            if (timestamp) {
                return dayjs(timestamp).tz(current.time.timezone.id).format(format)
            }
            return dayjs().tz(current.time.timezone.id).format(format)
        }

        return dayjs().format(format)
    }

    function dstTitle(index: number) {
        if (index == 0) {
            return t('time_of_day.index.last_change')
        }
        return t('time_of_day.index.next_change')
    }

    function dstDesc(item: any, index: number) {
        if (index == 0) {
            if (item.new_dst > 0) {
                return t('time_of_day.index.summer_started')
            }
            return t('time_of_day.index.winter_started')
        }
        if (item.new_dst > 0) {
            return t('time_of_day.index.summer_starts')
        }
        return t('time_of_day.index.winter_starts')
    }

    function dstNote(item: any) {
        var str = moment(item.timestamp).tz(current.time.timezone.id).format('YYYY-MM-DDTHH:mm:ss')
        var str2 = moment(item.timestamp - 1).tz(current.time.timezone.id).format('YYYY-MM-DDTHH:mm:ss')
        console.log(str, str2)
        debugger
        return 'Time was set forward 1 hour from 02:00 to 03:00.\nTime zone changed to UTC-7, Pacific Daylight Time (PDT).'
    }

    function isNight() {
        var hour = new Date().getHours()
        if (current) {
            var strHour = moment().tz(current.time.timezone.id).format('H')
            hour = parseInt(strHour)
        }

        if (hour >= 18 || hour < 6) {
            return true
        }
        return false
    }

    function dstModalContent() {
        return <View className="modal_bg">
            {
                current.time_changes.map((item, index) => {
                    return <View className="dst_content" key={index}>
                        <View className="dst_item">
                            <View className="dst_card">
                                <Text className="month">{formatTime('MMMM', item.timestamp)}</Text>
                                <Text className="day">{formatTime('D', item.timestamp)}</Text>
                                <Text className="week">{formatTime('dddd', item.timestamp)}</Text>
                                <Text className="year">{formatTime('YYYY', item.timestamp)}</Text>
                            </View>
                        </View>
                        <View style={{ flex: 1 }}>
                            <Text className="dst_title">{dstTitle(index)}</Text>
                            <Text className="dst_desc">{dstDesc(item, index)}</Text>
                            <Text className="dst_note">{dstNote(item)}</Text>
                        </View>
                    </View>
                })
            }

        </View>
    }

    return <View className="page_container">
        <View style={{ position: 'relative' }}>
            {
                ring()
            }
            <View className="ring_center">
                <Image className="sun" src={isNight() ? require('@assets/index_time/moon.png') : require('@assets/index_time/sun.png')} />
                <Text className="time">{formatTime('HH:mm:ss')}</Text>
                <Text className="date">{global.language == 'en' ? formatTime('dddd, MMM DD') : formatTime('MMMD dddd')}</Text>
            </View>
        </View>

        <View className="location">
            <Image className="location_icon" src={require('@assets/index_time/pin.png')} />
            <Text className="location_text">{current ? getLocation() : t('time_of_day.index.unknown')}</Text>
        </View>

        <View style={{ flexDirection: 'row', marginTop: 10, alignItems: 'center' }} onClick={() => {
            if (current && current.time && current.time.timezone.use_dst) {
                setShowDst(true)
            }
        }}>
            <Text className="timezone">{current ? getTimezone() : 'UTC+8'}</Text>
            {
                current && current.time && current.time.timezone.use_dst && <Image className="location_icon" src={require('@assets/index_time/arrow_right.png')} />
            }

        </View>


        <View className="btn_bg" onClick={goMap}>
            <Text className="btn_text">{t('time_of_day.index.pick_location')}</Text>
            <Image className="more" src={require('@assets/index_time/more.png')} />
        </View>
        <View className="footer" onClick={() => setShowLanguage(true)}>
            <Text className="footer_text">{isEn ? 'English' : '中文'}</Text>
            <Image className="footer_icon" src={require('@assets/index_time/arrow.png')} />
        </View>
        {
            showLanguage && <Modal
                testInfo={null}
                themeIsWhite={true}
                dismiss={() => {
                    setShowLanguage(false)
                }}
                confirm={() => { }}>
                {
                    languageModalContent()
                }
            </Modal>
        }
        {
            showDst && <Modal
                testInfo={null}
                themeIsWhite={true}
                dismiss={() => {
                    setShowDst(false)
                }}
                confirm={() => { }}>
                {
                    dstModalContent()
                }
            </Modal>
        }
    </View>
}