import React from 'react';
import classNames from 'classnames';
import css from '../components/FormCustomerDetails/index.module.css';
import Input from '../blocks/Input';
import { geocodeByAddress } from 'react-places-autocomplete';
import * as R from 'ramda';
import GoogleSVG from '../assets/icons/google.svg';
import LocationSVG from '../assets/icons/location-icon.svg';

export const getCity = (addressArray): string => {
  let city = '';
  for (let i = 0; i < addressArray.length; i++) {
    if (
      addressArray[i].types[0] &&
      ('locality' === addressArray[i].types[0] ||
        'postal_town' === addressArray[i].types[0])
    ) {
      city = addressArray[i].long_name;
      return city;
    }
  }
};

export const getStreetName = (addressArray): string => {
  let streetName = '';
  for (let i = 0; i < addressArray.length; i++) {
    if (addressArray[i].types[0] && 'route' === addressArray[i].types[0]) {
      streetName = addressArray[i].long_name;
      return streetName;
    }
  }
};

export const getStreetNumber = (addressArray): string => {
  let streetNumber = '';
  for (let i = 0; i < addressArray.length; i++) {
    if (
      addressArray[i].types[0] &&
      'street_number' === addressArray[i].types[0]
    ) {
      streetNumber = addressArray[i].long_name;
      return streetNumber;
    }
  }
};

export const getCountry = (addressArray): string => {
  let country = '';
  for (let i = 0; i < addressArray.length; i++) {
    if (addressArray[i].types[0] && 'country' === addressArray[i].types[0]) {
      country = addressArray[i].long_name;
      return country;
    }
  }
};

export const getZipCode = (addressArray): string => {
  let postalCode = '';
  for (let i = 0; i < addressArray.length; i++) {
    if (
      addressArray[i].types[0] &&
      'postal_code' === addressArray[i].types[0]
    ) {
      postalCode = addressArray[i].long_name;
      return postalCode;
    }
  }
};

export const autocompleteDebounce = (
  isAutocomplete,
  setAutocomplete,
  field,
  wait,
): void => {
  if (isAutocomplete == '') {
    let timeout;
    if (timeout) clearTimeout(timeout);
    setAutocomplete(field);
    timeout = setTimeout(() => {
      timeout = null;
      setAutocomplete('');
    }, wait);
  }
};

export const searchDropdown = ({
  suggestions,
  getSuggestionItemProps,
}): JSX.Element => (
  <div className="container">
    {suggestions.length > 0 && (
      <div className="autocomplete-container">
        {suggestions.map(suggestion => {
          const className = classNames('suggestion-item', {
            'suggestion-item--active': suggestion.active,
          });
          return (
            <div
              key={suggestion}
              {...getSuggestionItemProps(suggestion, { className })}
            >
              <span>
                <LocationSVG className="marker-logo" /> {suggestion.description}
              </span>
            </div>
          );
        })}
        <div className="dropdown-footer">
          <GoogleSVG className="google-logo" />
        </div>
      </div>
    )}
  </div>
);

export const renderAutocomplete = (
  checkIfKeyBoardOpen,
  getInputProps,
  suggestions,
  getSuggestionItemProps,
  label,
  value,
  touched,
  errors,
  setFieldTouched,
  type,
  name,
  autocomplete,
): JSX.Element => (
  <div className={css.formRegister__input}>
    <Input
      style={'booking'}
      name={name}
      autocomplete={autocomplete}
      type={type}
      label={label}
      required
      value={value}
      error={touched && errors}
      {...getInputProps({
        onFocus: () => {
          checkIfKeyBoardOpen(true);
        },
        onBlur: () => {
          checkIfKeyBoardOpen(false);
          setFieldTouched(name, true);
        },
      })}
    />
    {searchDropdown({ suggestions, getSuggestionItemProps })}
  </div>
);

export const checkIfAddressIsValid = async (
  callback,
  data,
  bool,
  openModal,
  setPosition,
): Promise<void> => {
  const address =
    data.streetNr +
    ' ' +
    data.street +
    ' ' +
    data.city +
    ' ' +
    data.country +
    ' ' +
    data.zip;
  try {
    data.country =
      data.country.toLowerCase() === 'uk' ? 'United Kingdom' : data.country;
    const results = await geocodeByAddress(address);
    const addressArray = results[0].address_components;
    const cityName = getCity(addressArray);
    const zip = getZipCode(addressArray);
    const streetName = getStreetName(addressArray);
    const streetNumber = getStreetNumber(addressArray);
    const country = getCountry(addressArray);
    const position = {
      latitude: results[0].geometry.location.lat(),
      longitude: results[0].geometry.location.lng(),
    };
    const isPartialMatch = R.hasIn('partial_match');
    if (
      results.length > 0 &&
      cityName &&
      zip &&
      streetName &&
      streetNumber &&
      data.country.toLowerCase() === country.toLowerCase() &&
      !isPartialMatch(Object.assign({}, ...results))
    ) {
      bool.current = true;
      setPosition(position);
      callback();
    } else {
      bool.current = false;
      setPosition(
        data.country.toLowerCase() === country.toLowerCase() ? position : null,
      );
      openModal(data, bool);
    }
  } catch (err) {
    bool.current = false;
    setPosition(null);
    openModal(data, bool);
  }
};
