import React, { useEffect, Fragment, useState } from 'react';
import Styled from 'styled-components/native';
import Theme from '~/Themes';
import { Util } from '~/Utils/utils';
import { Text, View } from 'react-native';
import { useToast } from '~/Components/UIControls/Message';
import fetchWeather, { applyWeatherName } from '~/Utils/weather';
import session from '~/Utils/session';
import IconButton from '~/Components/UIControls/IconButton';
import { TouchableOpacity } from 'react-native-gesture-handler';

const Container = Styled.View`
    flex: 1;
    flex-direction: column;
    padding-left: 30px;
    padding-right: 30px;
    justify-content: center;
`;
const Top = Styled.View`
    flex-direction: row;
    width: 100%;
    height: 50px;
    align-items: center;
`;
const WeatherName = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    include-font-padding: false;
    padding-top:5;
    font-size: 21;
    line-height: 25;
    letter-spacing: -1.05;
    color: black;
    padding-left:10px;
`;
const WeatherDetail = Styled.View`
    flex: 1;
    flex-direction: row;
    padding-left: 10px;
    align-items:center;
    justify-content:flex-start;
`;
const WeatherMinMax = Styled.Text`
    font-family: ${Theme.Fonts.DemiLight};
    include-font-padding: false;
    font-size: 15;
    line-height: 18;
    letter-spacing: -0.6;
    color: black;
    margin-top:3px;
`;
const WeatherDust = Styled.Text`
    font-family: ${Theme.Fonts.Light};
    include-font-padding: false;
    font-size: 10;
    line-height: 13;
    letter-spacing: -0.5;
    color: black;
`;
const WeatherTemp = Styled.View`
    flex-direction:row;
    justify-content: flex-end;
`;
const TempText = Styled.Text`
    font-family: ${Theme.Fonts.RobotoRegular};
    include-font-padding: false;
    font-size: 30;
    line-height: 58;
    letter-spacing:-1.5;
    color: black;
`;
const TempMark = Styled.Text`
    font-family: ${Theme.Fonts.Regular};
    include-font-padding: false;
    font-size: 18;
    line-height: 58;
    letter-spacing:-0.9;
    color: black;
`;

const Bottom = Styled.View`
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
    height: 50px;
`;
const BottomItem = Styled.View`
    flex-direction: column;
    height: 100%;
    align-items: center;
    justify-content: center;
`;
const BottomTitle = Styled.Text`
    font-family: ${Theme.Fonts.Medium};
    include-font-padding: false;
    font-size: 12;
    line-height: 17;
    letter-spacing:-0.6;
    color: black;
`;
const BottomValue = Styled.Text`
    font-family: ${Theme.Fonts.Light};
    include-font-padding: false;
    font-size: 11;
    line-height: 17;
    letter-spacing:-0.55;
    color: black;
`;
const Blue = Styled.Text`
    color: #4f57f4;
`;

const weatherIcons = {
    보통: '/weather/day',
    맑음: '/weather/day',
    구름조금: '/weather/cloudy-day-3',
    구름많음: '/weather/cloudy-day-3',
    흐림: '/weather/cloudy',
    비: '/weather/rainy-6',
    소나기: '/weather/rainy-1',
    눈비: '/weather/rainy-7',
    눈: '/weather/snowy-6',
};

let showInfoTimer = null;
  
export default Weather = ({ userinfo = {}, style = {}, doNotFetch=false, weatherinfo = null }) => {
    const [weather, setWeather] = useState(weatherinfo == null ? null : applyWeatherName(weatherinfo));
    const { showMessage } = useToast();
    const [showInfo, setShowInfo] = useState(false);

    useEffect(() => {
        if(!doNotFetch) {
            fetchWeather({
                    sido: userinfo.ApiSido,
                    sigun: userinfo.ApiSigun,
                },
                data => {
                    setWeather(data);
                },
                e => {
                    showMessage(e.message);
                },
            );
        }
    }, [userinfo]);

    useEffect(() => {
        if(doNotFetch) {
            setWeather(weatherinfo == null ? null : applyWeatherName(weatherinfo));
        }
    }, [weatherinfo]);
    
    const WeatherIcon = Util.svg(weatherIcons[Util.get(weather, "Weather", "보통")]);

    return (
        <Container style={style}>
            <Top>
                {WeatherIcon && <WeatherIcon width={50} height={50} />}
                <WeatherName>{Util.get(weather, "Weather", "보통")}</WeatherName>
                <WeatherDetail>
                    <WeatherMinMax>최고 {Util.get(weather, "HighTemp", 0)}℃ / 최저 {Util.get(weather, "LowTemp", 0)}℃ </WeatherMinMax>
                    <IconButton iconFamily="AntDesign" iconName="infocirlce" color="#595959" size={14} onPress={() => { 
                        setShowInfo(!showInfo);  
                        if(showInfoTimer) {
                            clearTimeout(showInfoTimer);
                            showInfoTimer = null;
                        }
                        showInfoTimer = setTimeout(() => {
                            setShowInfo(false);
                            showInfoTimer = null;
                        }, 3000);
                    }} />
                </WeatherDetail>
                <WeatherTemp>
                    <TempText>{Util.get(weather, "CurrentTemp", 0)}</TempText>
                    <TempMark> ℃</TempMark>
                </WeatherTemp>
            </Top>
            <Bottom>
                <BottomItem><BottomTitle>미세먼지</BottomTitle><BottomValue>{Util.get(weather, "Pm10", 0)}㎍/㎥ <Blue>{Util.get(weather, "Pm10Grade", 0)}</Blue></BottomValue></BottomItem>
                <BottomItem><BottomTitle>초미세먼지</BottomTitle><BottomValue>{Util.get(weather, "Pm25", 0)}㎍/㎥ <Blue>{Util.get(weather, "Pm25Grade", 0)}</Blue></BottomValue></BottomItem>
                <BottomItem><BottomTitle>강수량</BottomTitle><BottomValue>{Util.get(weather, "Rain", 0)}mm</BottomValue></BottomItem>
                <BottomItem><BottomTitle>현재바람</BottomTitle><BottomValue>{Util.get(weather, "WindDirection", 0)} {Util.get(weather, "WindSpeed", 0)}m/s</BottomValue></BottomItem>
                <BottomItem><BottomTitle>현재습도</BottomTitle><BottomValue>{Util.get(weather, "Humidity", 0)}%</BottomValue></BottomItem>
                {showInfo && (
                    <View 
                        style={{ 
                            position:'absolute', 
                            left:-15, right:-15,
                            top:0, bottom:-5,
                            alignItems:'center', 
                            justifyContent:'center',
                            backgroundColor:'#595959',
                            borderRadius:8,
                            paddingHorizontal:10
                        }}>
                        <TouchableOpacity onPress={() => { setShowInfo(false) }}>
                            <Text style={{fontFamily: Theme.Fonts.Regular, fontSize:11, color:'white'}}>
                                현지사정이나 수신상태에 의해 차이가 발생할 수 있습니다. 제공(환경부/한국환경공단)
                            </Text>
                        </TouchableOpacity>
                    </View>
                )}
            </Bottom>
        </Container>
    );
};
