import React from 'react'
import Slider from 'react-slick'
import styled from 'styled-components'
import {Box, Div, Row, Cell, Column, Flex, ErrorFlex, Button, FlexWithBottomBorder, FlexWithVerticalBorders} from '../components'
import {Info} from './index'
import {Text, Title, Note, MainText} from '../components/typography'
import {space} from 'styled-system'

const settings = {
    dots: true,
    infinite: false,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1
}

const formatDate = (date) => {
    let monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    let day = date.getDate();
    let monthIndex = date.getMonth();
    let year = date.getFullYear();
    return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

const Link = styled.a`
    width: 100%;
    color: white; 
    text-decoration: none;
`

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

const formatTime = (timeArray) => {
    return timeArray.reduce((acc, time) => {
        if (time < 10) return `${acc}${acc.length ? ':' : ''}0${time}`
        else return `${acc}${acc.length ? ':' : ''}${time}`
    }, '')
}

const formatDuration = (duration) => {
    const hours = Math.floor(duration / 3600000)
    const minutes = Math.floor((duration % 3600000) / 60000)
    return `${hours}h ${minutes}m`
}

const FlightRowContent = ({date, from, to, fromTime, toTime, stops, duration}) =>
    <Column fill justifyContent="center">
        <MainText lineHeight={2} display={['initial', 'initial', 'initial', 'none']} mb={20}>{date}</MainText>
        <Flex>
            <Flex pr={20} alignItems="center" justifyContent={['flex-end', 'flex-end', 'flex-end', 'space-between']} flex={[1, 1, 1, 3]}>
                <MainText display={['none', 'none', 'none', 'initial']} mr={20}>{date}</MainText>
                <Column alignItems="flex-end">
                    <MainText display={['none', 'none', 'initial', 'initial']} textAlign="right" mb={5}>{from.city} ({from.airportCode})</MainText>
                    <MainText display={['initial', 'initial', 'none', 'none']} textAlign="right" mb={5}>{fromTime} {from.airportCode}</MainText>
                    <Note display={['none', 'none', 'initial', 'initial']} textAlign="right">{from.airport}, {from.country}</Note>
                    <Note display={['initial', 'initial', 'none', 'none']} textAlign="right">{from.city}</Note>
                </Column>
            </Flex>
            <FlexWithVerticalBorders px={20} alignItems="center">
                <MainText display={['none', 'none', 'initial', 'initial']}>{fromTime}</MainText>
                <Column alignItems="center">
                    <Text>{duration}</Text>
                    <Arrow my={20} mx={[0, 0, 20, 20]} />
                    <Text style={{
                        opacity: stops ? 1 : 0,
                        userSelect: stops ? 'auto' : 'none',
                    }}>
                        {stops} {stops > 1 ? 'medzipristatia' : 'medzipristatie'}
                    </Text>
                </Column>
                <MainText display={['none', 'none', 'initial', 'initial']}>{toTime}</MainText>
            </FlexWithVerticalBorders>
            <Flex pl={20} alignItems="center" flex={1}>
                <Column>
                    <MainText display={['none', 'none', 'initial', 'initial']} mb={5}>{to.city} ({to.airportCode})</MainText>
                    <MainText display={['initial', 'initial', 'none', 'none']} mb={5}>{toTime} {to.airportCode}</MainText>
                    <Note display={['none', 'none', 'initial', 'initial']}>{to.airport}, {to.country}</Note>
                    <Note display={['initial', 'initial', 'none', 'none']}>{to.city}</Note>
                </Column>
            </Flex>
        </Flex>
    </Column>

const Results = (props) => {
    const {airportCodes, flights} = props.data
    const {passengerCount} = props.formValues
    if (!flights.length) return <ErrorFlex alignItems="center" justifyContent="center"><MainText color="red" my={20} mx={20} >Neboli nájdené žiadne letové ponuky.</MainText></ErrorFlex>
    return <Div style={{overflowX: 'hidden'}}>
        <Div mx={[-15, 0, 0, 0]} my={80} px={[0, 24, 24, 24]}>
            <Slider {...settings}>
                {flights.map(flight => {
                    const passengers = `${passengerCount.adt}${passengerCount.yth}${passengerCount.chd}${passengerCount.inf}E_${passengerCount.ythYears.join('-')}_${passengerCount.chdYears.join('-')}`
                    const thereTrip = flight.thereTrips[0]
                    const backTrip = flight.backTrips[0]
                    const thereDate = new Date(flight.thereDate[0], flight.thereDate[1] - 1, flight.thereDate[2])
                    const backDate = new Date(flight.backDate[0], flight.backDate[1] - 1, flight.backDate[2])
                    const there = {
                        from: airportCodes[thereTrip.from],
                        fromTime: formatTime([thereTrip.departureDateTime[3], thereTrip.departureDateTime[4]]),
                        to: airportCodes[thereTrip.to],
                        toTime: formatTime([thereTrip.arrivalDateTime[3], thereTrip.arrivalDateTime[4]]),
                        stops: thereTrip.segments.length - 1,
                        duration: formatDuration(thereTrip.duration),
                    }
                    const back = {
                        from: airportCodes[backTrip.from],
                        fromTime: formatTime([backTrip.departureDateTime[3], backTrip.departureDateTime[4]]),
                        to: airportCodes[backTrip.to],
                        toTime: formatTime([backTrip.arrivalDateTime[3], backTrip.arrivalDateTime[4]]),
                        stops: backTrip.segments.length - 1,
                        duration: formatDuration(backTrip.duration),
                    }
                    const link = "https://nove.letenky.sk/metasearch/T:1,P:" + passengers + ",TD:" + thereTrip.departureDateTime[0] + ";" + thereTrip.departureDateTime[1] + ";" + thereTrip.departureDateTime[2] + ";" + thereTrip.departureDateTime[3] + ";" + thereTrip.departureDateTime[4] + ",TA:" + thereTrip.arrivalDateTime[0] + ";" + thereTrip.arrivalDateTime[1] + ";" + thereTrip.arrivalDateTime[2] + ";" + thereTrip.arrivalDateTime[3] + ";" + thereTrip.arrivalDateTime[4] + ",TF:A" + there.from.airportCode + ",TT:A" + there.to.airportCode + ",BD:" + backTrip.departureDateTime[0] + ";" + backTrip.departureDateTime[1] + ";" + backTrip.departureDateTime[2] + ";" + backTrip.departureDateTime[3] + ";" + backTrip.departureDateTime[4] + ",BA:" + backTrip.arrivalDateTime[0] + ";" + backTrip.arrivalDateTime[1] + ";" + backTrip.arrivalDateTime[2] + ";" + backTrip.arrivalDateTime[3] + ";" + backTrip.arrivalDateTime[4] + ",BF:A" + back.from.airportCode + ",BT:A" + back.to.airportCode + ",PR:" + flight.price +",TK:1V07SS5YqCRK3RZP1UdO0rRSb94rXH99,SE:ULVPCJ44HHY="
                    return (
                        <Cell>
                            <Box p={25}>
                                <Row>
                                    <Cell width={[1, 1, 1, 4 / 5]}>
                                        <Column height={300}>
                                            <FlexWithBottomBorder pb={25} flex={1}>
                                                <FlightRowContent
                                                    date={formatDate(thereDate)}
                                                    from={there.from}
                                                    to={there.to}
                                                    fromTime={there.fromTime}
                                                    toTime={there.toTime}
                                                    stops={there.stops}
                                                    duration={there.duration}
                                                />
                                            </FlexWithBottomBorder>
                                            <Flex pt={25} flex={1}>
                                                <FlightRowContent
                                                    date={formatDate(backDate)}
                                                    from={back.from}
                                                    to={back.to}
                                                    fromTime={back.fromTime}
                                                    toTime={back.toTime}
                                                    stops={back.stops}
                                                    duration={back.duration}
                                                />
                                            </Flex>
                                        </Column>
                                    </Cell>
                                    <Cell width={[1, 1, 1, 1 / 5]}>
                                        <Column mt={[20, 20, 20, 0]} height="100%" justifyContent="center">
                                            <Flex alignItems="center" justifyContent="center">
                                                <Title>{Math.round(flight.price)}</Title>
                                                <Text ml={5} fontSize={16} fontWeight={500}>€</Text>
                                            </Flex>
                                            <Flex  mt={15}>
                                                <Link rel="noopener" target="_blank" href={link}>
                                                     <Button>Rezervuj</Button>
                                                </Link>
                                            </Flex>
                                        </Column>
                                    </Cell>
                                </Row>
                            </Box>
                        </Cell>
                    )
                })}
            </Slider>
        </Div>
        <Info destination={props.data} />
    </Div>
}

export default Results
