import React, {Component} from 'react'
import styled from 'styled-components'
import axios from 'axios'
import {space} from 'styled-system'

import {Box, Div, Row, Cell, Column, Flex, ErrorFlex, Button, FlexWithBottomBorder, FlexWithVerticalBorders} from '../components'
import {Text, Title, Note, MainText} from '../components/typography'

import db from '../db'

const stringifyAirports = (airports) => {
    return airports.reduce((accumulator, a, i) => i === 0 ? a : accumulator.concat(` ${a}`), '')
}

const addDays = (date, days) => {
  let result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

const Arrow = styled.div`
  width: 50px;
  height: 2px;
  background-color: ${props => props.theme.colors.white};
  position: relative;
  ${space}
  &::after {
    content: '';
    position: absolute;
    right: 0;
    border-top: 2px solid ${props => props.theme.colors.white};
    border-right: 2px solid ${props => props.theme.colors.white};
    height: 10px;
    width: 10px;
    top: 50%;
    transform: translate(0,-50%) rotate(45deg);
  }
`

const Container = styled(Column)`
	background-color: ${props => props.theme.colors.darkGrey};
	position: absolute;
	z-index: 260;
	transition: top 0.5s ease;
	top: ${props => props.top}px;
	right: 15px;
	border-radius: 2px;
    ${props => props.theme.shadow}
`

const DelCard = styled(Cell)`
    cursor: pointer;
    justify-self: end;
`

const ToCard = styled(Cell)`
    cursor: pointer;
    justify-self: start;
`

const NotifCard = (props) => {
    return(
        <Cell my={10} mx={10}>
            <Flex>
                <ToCard onClick={() => {props.getData(); props.resetData()}}>
                    <Flex alignItems="center">
                        <Text color="white">{props.dataForm.takeOff.text}</Text>
                        <Arrow mx={7}/>
                        <Text color="white">{props.dataForm.land.text}</Text>
                    </Flex>
                </ToCard>
                <DelCard  onClick={props.resetData}>
                    <Text color="orange">x</Text>
                </DelCard>
            </Flex>
        </Cell>
    )
}

class Notiffication extends Component {
	state = {
		data: [],
		formData: []
	}

  	componentDidMount() {
        const startAct = new Date(new Date().getTime() + 86400000)
  		db.searches.each(record => {
            let oldStartDate = record.values.startDate
            let oldEndDate = record.values.endDate
            let diffTime = Math.abs(oldEndDate.getTime() - oldStartDate.getTime())
            let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

            const endAct = addDays(startAct, diffDays)

  			axios.get(`https://www.pelikan.sk/gf1/pelijee-sk/admin/getsession`)
                .then((res) => {
                    axios({
                        method: 'post',
                        url: 'https://www.pelikan.sk/gf1/pelijee-sk/mobile/search?limit=10&offset=0&tabIdentifier=' + res.data.sessionToken,
                        data: {
                            'there': {
                                'date': [
                                    startAct.getFullYear(),
                                    startAct.getMonth() + 1,
                                    startAct.getDate(),
                                ],
                                'from': {
                                    'code': stringifyAirports(record.values.takeOff.airports),
                                    'type': 'AIRPORT',
                                },
                                'to':{
                                    'code': stringifyAirports(record.values.land.airports),
                                    'type': 'AIRPORT',
                                }
                            },
                            'passengerCount': record.values.passengerCount,
                            'travelClass': 'ECONOMY',
                            'rangeDates': true,
                            'back': {
                                'date': [
                                    endAct.getFullYear(),
                                    endAct.getMonth() + 1,
                                    endAct.getDate(),
                                ],
                                'to': {
                                    'code': stringifyAirports(record.values.takeOff.airports),
                                    'type': 'AIRPORT',
                                },
                                'from':{
                                    'code': stringifyAirports(record.values.land.airports),
                                    'type': 'AIRPORT',
                                }
                            }
                        }
                    }).then((res) => {
                        console.log(res.data)
                        console.log(record.values)
                        if (res.data.flights) {
                        	if (res.data.flights[0].price < record.price) {
                        		let data = this.state.data.slice()
                                let formData = this.state.formData.slice()
		                        data.push(res.data)
                                formData.push(record.values)
		                        this.setState({data, formData})
                        	}
                        }  
                    })
                })
                .catch((err) => {
                    console.log(err);
                });
  		})
  	}

	render() {
        const cards = []
        const {data, formData} = this.state

        formData && formData.map((oneFormData, i) => {
            cards.push(
                <NotifCard 
                    resetData={(() => this.setState(
                        {formData: formData.filter(oneData => oneData !== oneFormData),
                        data: data.filter(oneData => oneData !== data[i])})
                    )} 
                    dataReal={data[i]} 
                    dataForm={oneFormData}
                    getData={() => this.props.getData(data[i], oneFormData)}
                />
            )
        })
        
		return(
			<Container top={formData.length ? 16 : -100}>
                <Cell mx={5} mt= {5}>
                    <MainText color="white">Výhodné ponuky:</MainText>
                </Cell>
                {cards}
            </Container>
		)
	}
}

export default Notiffication