import React from 'react'
import styled from 'styled-components'
import axios from 'axios'
import {Cell, Row, Button, Input, Icon, InputHolder, InputWithSuggestions, TravelersInput, Spinner} from '../components'
import DatePicker from 'react-datepicker'
import {Form, Field} from 'react-final-form'
import "react-datepicker/dist/react-datepicker.css"

import db from '../db'

const StyledRow = styled(Row)`
  & > * > * {
    margin-top: 10px;
    margin-bottom: 10px;
  }
`

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

const calendarProps = {
    dateFormat: 'd MMM YYYY',
    customInput: <Input aria-label="Date input field" />,
}

const initialValues = {
    takeOff: {text: '', airports: null},
    land: {text: '', airports: null},
    startDate: new Date(new Date().getTime() + 86400000),
    endDate: new Date(new Date().getTime() + 691200000),
    passengerCount: {
        adt: 1,
        yth: 0,
        chd: 0,
        inf: 0,
        ythYears: [],
        chdYears: [],
    }
}

class SearchForm extends React.Component {
    state = {
        loading: false,
    }

    render() {
        return (
            <Form
                initialValues={initialValues}
                onSubmit={(values) => {
                    this.setState({loading: true})
                    this.props.getFormData(values)
                    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': [
                                            values.startDate.getFullYear(),
                                            values.startDate.getMonth() + 1,
                                            values.startDate.getDate(),
                                        ],
                                        'from': {
                                            'code': stringifyAirports(values.takeOff.airports),
                                            //'type': values.takeOff.airports.length > 1 ? 'MULTI_CITY' : 'AIRPORT',
                                            'type': 'AIRPORT',
                                        },
                                        'to':{
                                            'code': stringifyAirports(values.land.airports),
                                            //'type': values.land.airports.length > 1 ? 'MULTI_CITY' : 'AIRPORT',
                                            'type': 'AIRPORT',
                                        }
                                    },
                                    'passengerCount': values.passengerCount,
                                    'travelClass': 'ECONOMY',
                                    'rangeDates': true,
                                    'back': {
                                        'date': [
                                            values.endDate.getFullYear(),
                                            values.endDate.getMonth() + 1,
                                            values.endDate.getDate(),
                                        ],
                                        'to': {
                                            'code': stringifyAirports(values.takeOff.airports),
                                            //'type': values.takeOff.airports.length > 1 ? 'MULTI_CITY' : 'AIRPORT',
                                            'type': 'AIRPORT',
                                        },
                                        'from':{
                                            'code': stringifyAirports(values.land.airports),
                                            //'type': values.land.airports.length > 1 ? 'MULTI_CITY' : 'AIRPORT',
                                            'type': 'AIRPORT',
                                        }
                                    }
                                }
                            }).then((res) => {
                                this.setState({loading: false})
                                this.props.getResults(res.data)
                                
                                db.transaction('rw', db.searches, () => {
                                    db.searches.where('takeOff').equals(values.takeOff.text).and(dest => dest.land === values.land.text).and(price => price.price >= res.data.flights[0].price).delete()
                                    db.searches.where('takeOff').equals(values.takeOff.text).and(dest => dest.land === values.land.text).and(price => price.price < res.data.flights[0].price).delete()
                                    db.searches.add({price: res.data.flights[0].price, takeOff: values.takeOff.text, land: values.land.text, startDate: values.startDate, endDate: values.endDate, values: values})                                    
                                }).catch((e) => {
                                    console.log(e)
                                });
                            })
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                }}
                validate={values => null}
                render={({handleSubmit, values, submitSucceeded, dirtySinceLastSubmit}) => (
                    <form onSubmit={handleSubmit}>
                        <StyledRow>
                            <Cell width={[1, 1 / 2, 1 / 3, 1 / 6]}>
                                <Field
                                    name="takeOff"
                                    placeholder="Odlet"
                                    component={InputWithSuggestions}
                                />
                            </Cell>
                            <Cell width={[1, 1 / 2, 1 / 3, 1 / 6]}>
                                <Field
                                    name="land"
                                    placeholder="Prílet"
                                    land
                                    component={InputWithSuggestions}
                                />
                            </Cell>
                            <Cell width={[1, 1 / 2, 1 / 3, 1 / 6]}>
                                <InputHolder>
                                    <Field
                                        name="startDate"
                                        render={({input: {value, ...input}}) => (
                                            <DatePicker
                                                selected={value}
                                                selectsStart
                                                startDate={value}
                                                endDate={values.endDate}
                                                maxDate={values.endDate}
                                                placeholderText="From"
                                                {...input}
                                                {...calendarProps}
                                            />
                                        )}
                                    />
                                    <Icon className="fas fa-calendar-alt" />
                                </InputHolder>
                            </Cell>
                            <Cell width={[1, 1 / 2, 1 / 3, 1 / 6]}>
                                <InputHolder>
                                    <Field
                                        name="endDate"
                                        render={({input: {value, ...input}}) => (
                                            <DatePicker
                                                selected={value}
                                                selectsEnd
                                                startDate={values.startDate}
                                                endDate={value}
                                                minDate={values.startDate}
                                                placeholderText="To"
                                                {...input}
                                                {...calendarProps}
                                            />
                                        )}
                                    />
                                    <Icon className="fas fa-calendar-alt" />
                                </InputHolder>
                            </Cell>
                            <Cell width={[1, 1 / 2, 1 / 3, 1 / 6]}>
                                <Field
                                    name="passengerCount"
                                    component={TravelersInput}
                                />
                            </Cell>
                            <Cell width={[1, 1 / 2, 1 / 3, 1 / 6]}>
                                <Button
                                    disabled={(submitSucceeded && !dirtySinceLastSubmit) || !values.takeOff.airports || !values.land.airports}
                                    type="submit">
                                    {this.state.loading ? <Spinner /> : 'Hľadať'}
                                </Button>
                            </Cell>
                        </StyledRow>
                    </form>
                )}
            />
        )
    }
}

export default SearchForm
