// This file is part of Coog. The COPYRIGHT file at the top level of
// this repository contains the full copyright notices and license terms.

import React, { FC, useState } from 'react';
import { GeoapifyGeocoderAutocomplete, GeoapifyContext } from '@coog/react-geocoder-autocomplete';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSpinner } from '@fortawesome/free-solid-svg-icons';
import cn from 'classnames';

import { OSMAddressFieldProps } from './OSMAddressField.types';

import '@geoapify/geocoder-autocomplete/styles/minimal.css';
import './OSMAddressField.scss';

const OSMAddressField: FC<OSMAddressFieldProps> = ({
  apiKey,
  language,
  value,
  eventEmitter,
  regions,
  placeholder,
  debounce = 500,
}: OSMAddressFieldProps): JSX.Element => {
  const [localValue, setLocalValue] = useState(value);
  const [loading, setLoading] = useState(false);

  // eslint-disable-next-line @typescript-eslint/ban-types
  const onPlaceSelect = (value: any): {} => {
    setLoading(false);
    eventEmitter(value?.properties?.formatted, value?.properties);
    return;
  };

  // eslint-disable-next-line @typescript-eslint/ban-types
  const onSuggestionChange = (value: any): {} => {
    setLoading(false);
    return;
  };

  const preprocessHook = (value: string): string => {
    setLoading(true);

    return value;
  };

  return apiKey ? (
    <div data-testid="OSMAddressField" className={cn('osm-address-field', { loading })}>
      <GeoapifyContext apiKey={apiKey}>
        <GeoapifyGeocoderAutocomplete
          placeholder={placeholder}
          value={localValue}
          lang={language}
          skipIcons
          skipDetails
          placeSelect={onPlaceSelect}
          suggestionsChange={onSuggestionChange}
          preprocessHook={preprocessHook}
          filterByCountryCode={regions}
          debounceDelay={debounce}
        />
        <div className="icon">
          <FontAwesomeIcon icon={faSpinner} spin />
        </div>
      </GeoapifyContext>
    </div>
  ) : (
    <div data-testid="OSMAddressField" className="osm-address-field">
      No apiKey found
    </div>
  );
};

export default OSMAddressField;

export { OSMAddressFieldProps };
