import React, {Component} from 'react'
import styled from 'styled-components'
import {Row, Div, Cell, Column, Flex, Button, Box, FlexWithBottomBorder} from '../components'
import {Text, Title, MainText} from '../components/typography'
import axios from 'axios'

const WEATHER_API = "70bcd9e3cd7043f882e184207193004"
const NUMBEO_API = "l3pypi524jp9dv"
const GEOCODE_API = "AIzaSyCNQWHTY5MxFeIXlWHQGnSOzhZaZGZ-EtI"

const Icon = styled.img`
  height: 40px;
  width: auto;
`

class Info extends Component {
	state = {
		toggleCollapse: false,
		weatherData: {},
		destData: {}
	}

	toggleCollapse = (e) => {
		if (this.state.toggleCollapse === false) {
			this.setState({toggleCollapse: true})
		} else {
			this.setState({toggleCollapse: false})
		}
	}

	formatDate = (date) => {
	    let d = new Date(date),
	        month = '' + (d.getMonth() + 1),
	        day = '' + d.getDate(),
	        year = d.getFullYear() - 1;

	    if (month.length < 2) month = '0' + month;
	    if (day.length < 2) day = '0' + day;

	    return [year, month, day].join('-');
	}

	safetyIcon = (destData) => {
		if (destData <= 20) {return <Icon src={'static/velmi_zle.svg'} alt="very low" />}
		if (destData > 20 && destData <= 40) {return <Icon src={'static/zle.svg'} alt="low" />}
		if (destData > 40 && destData <= 60) {return <Icon src={'static/normalne.svg'} alt="medium" />}
		if (destData > 60 && destData <= 80) {return <Icon src={'static/dobre.svg'} alt="good" />}
		if (destData > 80) {return <Icon src={'static/velmi_dobre.svg'} alt="very good" />}
	}

	lifeIcon = (destData) => {
		if (destData <= 50) {return <Icon src={'static/velmi_zle.svg'} alt="very low" />}
		if (destData > 50 && destData <= 80) {return <Icon src={'static/zle.svg'} alt="low" />}
		if (destData > 80 && destData <= 110) {return <Icon src={'static/normalne.svg'} alt="medium" />}
		if (destData > 110 && destData <= 150) {return <Icon src={'static/dobre.svg'} alt="good" />}
		if (destData > 150) {return <Icon src={'static/velmi_dobre.svg'} alt="very good" />}
	}

	trafficIcon = (destData) => {
		if (destData > 300) {return <Icon src={'static/velmi_zle.svg'} alt="very low" />}
		if (destData > 200 && destData <= 300) {return <Icon src={'static/zle.svg'} alt="low" />}
		if (destData > 150 && destData <= 200) {return <Icon src={'static/normalne.svg'} alt="medium" />}
		if (destData > 100 && destData <= 150) {return <Icon src={'static/dobre.svg'} alt="good" />}
		if (destData <= 100) {return <Icon src={'static/velmi_dobre.svg'} alt="very good" />}
	}
	
	rentIcon = (destData) => {
		if (destData > 80) {return <Icon src={'static/velmi_zle.svg'} alt="very low" />}
		if (destData > 60 && destData <= 80) {return <Icon src={'static/zle.svg'} alt="low" />}
		if (destData > 40 && destData <= 60) {return <Icon src={'static/normalne.svg'} alt="medium" />}
		if (destData > 20 && destData <= 40) {return <Icon src={'static/dobre.svg'} alt="good" />}
		if (destData <= 20) {return <Icon src={'static/velmi_dobre.svg'} alt="very good" />}
	}

	componentDidMount() {
		const to = this.props.destination.flights[0].thereTrips[0].to
		const destination = this.props.destination.airportCodes[to]
		const thereDate = new Date(this.props.destination.flights[0].thereDate[0], this.props.destination.flights[0].thereDate[1] - 1, this.props.destination.flights[0].thereDate[2])

		axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${destination.city}&key=${GEOCODE_API}`)
	    .then((res) => {
	      	let lat = res.data.results[0].geometry.location.lat;
	      	let lon = res.data.results[0].geometry.location.lng;
	      	return axios.get('https://api.worldweatheronline.com/premium/v1/past-weather.ashx', {
    			params: {
      				q: lat + ',' + lon,
      				date: this.formatDate(thereDate),
      				key: WEATHER_API,
      				format: 'json'
    			}
  			})
  			.then((res) => {
  				console.log(res)
  				this.setState({weatherData: res.data.data.weather[0]})
  				return axios.get('https://www.numbeo.com/api/indices', {
  					params: {
  						api_key: NUMBEO_API,
  						query: lat + ',' + lon
  					}
  				})
  			})
  			.then((res) => {
	    		console.log(res)
	    		this.setState({destData: res.data})
	    	})	
	    })
  		.catch(function (error) {
    		console.log(error);
  		})
	}

	componentDidUpdate(prevProps) {
		if (this.props !== prevProps) {
			const to = this.props.destination.flights[0].thereTrips[0].to
			const destination = this.props.destination.airportCodes[to]
			const thereDate = new Date(this.props.destination.flights[0].thereDate[0], this.props.destination.flights[0].thereDate[1] - 1, this.props.destination.flights[0].thereDate[2])

			axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${destination.city}&key=${GEOCODE_API}`)
		    .then((res) => {
		      	let lat = res.data.results[0].geometry.location.lat;
		      	let lon = res.data.results[0].geometry.location.lng;
		      	return axios.get('https://api.worldweatheronline.com/premium/v1/past-weather.ashx', {
	    			params: {
	      				q: lat + ',' + lon,
	      				date: this.formatDate(thereDate),
	      				key: WEATHER_API,
	      				format: 'json'
	    			}
	  			})
	  			.then((res) => {
	  				console.log(res)
	  				this.setState({weatherData: res.data.data.weather[0]})
	  				return axios.get('https://www.numbeo.com/api/indices', {
	  					params: {
	  						api_key: NUMBEO_API,
	  						query: lat + ',' + lon
	  					}
	  				})
	  			})
	  			.then((res) => {
		    		console.log(res)
		    		this.setState({destData: res.data})
		    	})	
		    })
	  		.catch(function (error) {
	    		console.log(error);
	  		})
		}
	}


	render() {
		return(
			<Div mx={[-15, 0, 0, 0]} px={[0, 24, 24, 24]}>
				<Flex fill justifyContent="center">
					<Cell width={[1, 1 / 2, 1 / 3, 1 / 4]}>
						<Button onClick={this.toggleCollapse} color="lightBlue" ><Text>Info o destinácii {this.state.toggleCollapse ? "⏶" : "⏷"}</Text></Button>
					</Cell>
				</Flex>
				{this.state.toggleCollapse &&
					<Div my={15}>
						<Cell>
							<Box>
								<Row>
									<Cell width={[1, 1, 1, 1]}>
										<Column fill minHeight={300} p={10}>
											<FlexWithBottomBorder pb={20} flex={1} alignItems="center">
												<Column ml={10} mt={10} fill justifyContent="center">
													<MainText>Odhad počasia v dobe príletu</MainText>
													<Flex mt={15}>
														<Flex alignItems="center" justifyContent={'space-around'} flexWrap="wrap" flex={1}>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]}>
									                            <Flex justifyContent="center">
									                            	<Text display={['initial', 'initial', 'initial', 'none']}>Najvyššia teplota:</Text>
									                            </Flex> 
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>Najvyššia teplota:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.state.weatherData.maxtempC}</Title>
								                            		<Text ml={5}>°C</Text>
								                            	</Flex>
									                        </Cell>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]}>
								                            	<Flex justifyContent="center">
								                            		<Text display={['initial', 'initial', 'initial', 'none']}>Najnižšia teplota:</Text>
								                            	</Flex> 
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>Najnižšia teplota:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.state.weatherData.mintempC}</Title>
								                            		<Text ml={5}>°C</Text>
								                            	</Flex>
								                            </Cell>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]} mt={[15, 15, 0, 0]}>
								                            	<Flex justifyContent="center">
								                            		<Text display={['initial', 'initial', 'initial', 'none']}>ø Dĺžka dňa:</Text>
								                            	</Flex> 
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>ø Dĺžka dňa:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.state.weatherData.sunHour}</Title>
								                            		<Text ml={5}>hod</Text>
								                            	</Flex>
								                            </Cell>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]} mt={[15, 15, 0, 0]}>
								                            	<Flex justifyContent="center">
								                            		<Text display={['initial', 'initial', 'initial', 'none']}>ø Sneh:</Text>
								                            	</Flex>
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>ø Sneh:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.state.weatherData.totalSnow_cm}</Title>
								                            		<Text ml={5}>cm</Text>
								                            	</Flex>
								                            </Cell>
								                        </Flex>
							                        </Flex>
							                    </Column>
						                    </FlexWithBottomBorder>
						                    <Flex pt={20} flex={1} alignItems="center">
							                    <Column ml={10} fill justifyContent="center">
							                    	<MainText>Ďalšie fakty o destinácii</MainText>
							                    	<Flex mt={15}>
							                    		<Flex alignItems="center" justifyContent={'space-around'} flexWrap="wrap" flex={1}>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]}>
									                            <Flex justifyContent="center">
									                            	<Text display={['initial', 'initial', 'initial', 'none']}>Bezpečnosť:</Text>
									                            </Flex> 
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>Bezpečnosť:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.safetyIcon(this.state.destData.safety_index)}</Title>
								                            	</Flex>
									                        </Cell>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]}>
								                            	<Flex justifyContent="center">
								                            		<Text display={['initial', 'initial', 'initial', 'none']}>Životná úroveň:</Text>
								                            	</Flex> 
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>Životná úroveň:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.lifeIcon(this.state.destData.quality_of_life_index)}</Title>
								                            	</Flex>
								                            </Cell>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]} mt={[15, 15, 0, 0]}>
								                            	<Flex justifyContent="center">
								                            		<Text display={['initial', 'initial', 'initial', 'none']}>Doprava:</Text>
								                            	</Flex> 
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>Doprava:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.trafficIcon(this.state.destData.traffic_inefficiency_index)}</Title>
								                            	</Flex>
								                            </Cell>
								                            <Cell width={[1 / 2, 1 / 2, 1 / 4, 1 / 4]} mt={[15, 15, 0, 0]}>
								                            	<Flex justifyContent="center">
								                            		<Text display={['initial', 'initial', 'initial', 'none']}>Cena ubytovania:</Text>
								                            	</Flex> 
								                            	<Flex alignItems="center" justifyContent="center">
								                            		<Text display={['none', 'none', 'none', 'initial']} mr={10}>Cena ubytovania:</Text>
								                            		<Title mt={[10, 10, 10, 0]}>{this.rentIcon(this.state.destData.rent_index)}</Title>
								                            	</Flex>
								                            </Cell>
								                        </Flex>
							                        </Flex>
							                    </Column>
						                    </Flex>
										</Column>
									</Cell>
								</Row>
							</Box>
						</Cell>
					</Div>
				}
			</Div>
		)
	}
}

export default Info