import React from 'react'
import styled from 'styled-components'
import axios from 'axios'
import Input from './Input'
import InputHolder from './InputHolder'
import Icon from './Icon'
import Spinner from './Spinner'
import {Column, Flex, Div} from './layout'

const Text = styled.p`
  font-size: 14px;
  color: ${props => props.theme.colors.darkGrey};
  padding: 0;
  margin: 0;
`

const Wrapper = styled(Column)`
  max-height: ${props => props.open ? 300 : 0}px;
  overflow: hidden;
  background-color: #ffffff;
  position: absolute;
  z-index: 100;
  top: 45px;
  left: 0;
  width: 300px;
  border-radius: 2px;
  min-width: 100%;
  ${props => props.theme.shadow}
`

const Suggestions = styled(Column)`
  overflow: auto;
`

const Bullet = styled.div`
  height: 3px;
  width: 3px;
  border-radius: 50%;
  background-color: ${props => props.theme.colors.darkGrey};
  margin-right: 5px;
`

const SuggestionWrapper = styled(Flex)`
  cursor: pointer;
  :hover {
    background-color: ${props => props.theme.colors.lightBlue};
  }
`


const Suggestion = ({text, airports, onSelect}) => (
    <Column>
        <SuggestionWrapper
            onClick={() => onSelect(text, airports)}
            alignItems="center"
            px={15}
            height={40}
        >
            <Text>{text}</Text>
        </SuggestionWrapper>
        {airports.map(airport =>
            <SuggestionWrapper
                onClick={() => onSelect(airport.airportName, [airport])}
                key={airport.code}
                alignItems="center"
                pl={30}
                pr={15}
                height={40}
            >
                <Bullet /><Text>{airport.airportName}</Text>
            </SuggestionWrapper>)}
    </Column>
)

class InputWithSuggestions extends React.Component {
    holder = null
    state = {
        loading: true,
        results: {cities: [], countries: []},
    }
    watchOutsideClick = (e) => {
        if (!this.holder.contains(e.target)) {
           this.props.input.onBlur()
        }
    }
    componentDidMount() {
        window.addEventListener('mousedown', this.watchOutsideClick)
    }
    onChange = (e) => {
        this.setState({loading: true})
        this.props.input.onChange({text: e.target.value, airports: null})
        this.getDest(e.target.value)
    }
    getDest = (value) => {
        axios({
            method: 'post',
            url: 'https://www.pelikan.sk/gf1/pelijee-sk/mobile/autocomplete2',
            data: {
                query: value
            }
        }).then((res) => {
            this.setState({results: res.data, loading: false});
        });
    }
    onSelect = (value, airports) => {
        const codes = airports.map(airport => airport.code)
        this.props.input.onChange({text: value, airports: codes})
        this.props.input.onBlur()
    }
    render() {
        const hasResults = this.state.results.countries.length > 0 || this.state.results.cities.length > 0
        const {input: {onChange, onBlur, value, ...input}, meta, land, ...props} = this.props
        return (
            <InputHolder ref={node => {this.holder = node}}>
                <Input
                    onChange={this.onChange}
                    value={value.text}
                    {...input}
                    {...props}
                    autoComplete="off"
                    aria-label="autocomplete2 input field"
                />
                <Wrapper open={meta.active && value.text.length > 0}>
                    <Suggestions>
                        {this.state.loading && <Flex justifyContent="center" p={10}><Spinner /></Flex>}
                        {!this.state.loading && hasResults &&
                        [...this.state.results.countries, ...this.state.results.cities].map(result =>
                            <Suggestion
                                onSelect={(value, airports) => this.onSelect(value, airports)}
                                key={result.name}
                                airports={result.airports}
                                text={result.name}
                            />
                        )}
                        {!this.state.loading && !hasResults && value.text.length > 0 &&
                        <Div p={10}>
                            <Text>Neboli nájdené žiadne zhody</Text>
                        </Div>}
                    </Suggestions>
                </Wrapper>
                <Icon className={`fas ${land ? 'fa-plane-arrival' : 'fa-plane-departure'}`} />
            </InputHolder>
        )
    }
}

export default InputWithSuggestions
