import "./kartografSearch.scss";
import WindowWidthType from "../utils/windowWidthType";
import { useState } from "@wordpress/element";
import KartografAutocompleteList from "./kartografAutocompleteList";
import useWindowSize from "../utils/resizeHook";
import EpakaApi from "./api/api";

import chevronRight from "./img/chevron_right_2nd.svg";
import { debounce } from "lodash";

const api = new EpakaApi();

const KartografSearch = (props) => {
  const [searchTerm, setSearchTerm] = useState(props.initialSearchTerm);
  const [autocompleteVisible, setAutocompleteVisible] = useState(false);
  const [addressAutocompleteElements, setAddressAutocompleteElements] =
    useState([]);
  const [pointsAutocompleteElements, setPointsAutocompleteElements] = useState(
    [],
  );
  const [autocompleteInactive, setAutocompleteInactive] = useState(false);
  const [autocompleteLoading, setAutocompleteLoading] = useState(false);

  const windowSize = useWindowSize();

  const buildRequestOptions = () => {
    const options = {
      cod_only: false,
      weight: 10,
      function: "odbior",
      withoutPrinter: false,
    };

    return options;
  };

  const handleSearchChange = debounce(async (value) => {
    setSearchTerm(value);

    if (value.length >= 1) {
      setAutocompleteVisible(true);
    } else {
      setAutocompleteVisible(false);
      setAddressAutocompleteElements([]);
      setPointsAutocompleteElements([]);
    }

    if (value.length >= 3) {
      setAutocompleteInactive(false);
      setAutocompleteLoading(true);
      let AddressAutocompleteQuery;
      let AddressQuery;

      if (/^[0-9]{2}-[0-9]{3}$/.test(value)) {
        AddressAutocompleteQuery = api.getFullNominatimSearch(
          value,
          props.country,
        );
      } else {
        AddressQuery = api.getFullNominatimSearch(value, props.country);
        AddressAutocompleteQuery = api.getAddressAutocomplete(
          value,
          props.country,
        );
      }

      const PointsAutocompleteQuery = api.requestPointsAutocomplete(
        value,
        props.courier,
        5,
        buildRequestOptions(),
      );

      const AddressAutocomplete = await AddressAutocompleteQuery;
      const PointsAutocomplete = await PointsAutocompleteQuery;
      let Address = [];
      if (AddressQuery !== null) {
        Address = await AddressQuery;
      }

      const mergedAutocomplete = [];
      const validTypes = [
        "administrative",
        "village",
        "hamlet",
        "isolated_dwelling",
        "farm",
        "allotments",
        "street",
        "house",
        "living_street",
        "service",
        "pedestrian",
        "road",
        "place",
      ];

      if (!!Address) {
        Address.forEach((item) => {
          if (validTypes.includes(item.type)) {
            mergedAutocomplete.push(item);
          }
        });
      }

      if (mergedAutocomplete.length < 3) {
        AddressAutocomplete.forEach((item) => {
          let exists = false;
          mergedAutocomplete.forEach((existingItem) => {
            if (existingItem.processed_name === item.processed_name) {
              exists = true;
            }
          });

          if (!exists && mergedAutocomplete.length < 3) {
            mergedAutocomplete.push(item);
          }
        });
      }

      setAddressAutocompleteElements(mergedAutocomplete);
      setPointsAutocompleteElements(PointsAutocomplete);
      setAutocompleteLoading(false);
    }
  }, 100);

  return (
    <div
      className={`kartografSearch ${autocompleteVisible ? "searchAreaFullscreen" : ""}`}
    >
      <div className={"epaka-w-100"}>
        <div className={"mapSearchInputWrapper"}>
          {props.windowSize === WindowWidthType.SM && (
            <img
              onClick={() => {
                props.closeMap();
              }}
              className={"mapSearchInputBackImg"}
              src={chevronRight}
              alt={"exit"}
            />
          )}
          <div className={"epaka-w-100"}>
            <i
              className={`mapSearchInputIcon ${!searchTerm ? "icon-search2" : "icon-iks"}`}
              onClick={() => handleSearchChange("")}
            ></i>
            <input
              className={"mapSearchInput epaka-w-100"}
              value={searchTerm}
              onChange={(event) => handleSearchChange(event.target.value)}
              placeholder={"Wpisz adres lub numer Punktu"}
            />
          </div>
        </div>
        {autocompleteVisible ? (
          <div className={"autocompleteListMapContainer"}>
            <KartografAutocompleteList
              searchTerm={searchTerm}
              loading={autocompleteLoading}
              addressAutocompleteElements={addressAutocompleteElements}
              pointAutocompleteElements={pointsAutocompleteElements}
              onClick={(item) => {
                setAutocompleteVisible(false);
                props.onListPositionClick(item);
              }}
              inactive={autocompleteInactive}
            />
          </div>
        ) : (
          <div>
            {windowSize >= WindowWidthType.MD && (
              <div className={"autocompleteListMapContainer"}>
                {props.results !== null && (
                  <div className={"autocompleteMapList"}>{props.results}</div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default KartografSearch;
