import {useRouter} from "next/router";
import {useState} from "react";

import styles from './shop-search.module.scss';
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faMagnifyingGlass} from "@fortawesome/free-solid-svg-icons";
import {buildShopParamsGET, findQueryParamsValue} from "../../libs/utils";

/* eslint-disable-next-line */
export interface ShopSearchProps {
  queries: { param: string, value: any }[];
}

export function ShopSearch({queries = []}: ShopSearchProps) {
  const router = useRouter();
  const [search, setSearch] = useState(findQueryParamsValue(queries, 'search') || '');

  /*useEffect(() => {
    if (subject === null) {
      const sub = new BehaviorSubject('');
      const client = new MeiliSearch({
        host: environment.meiliUrl,
        apiKey: environment.meiliApiKey
      })
      setSubject(sub);
      setClient(client);
    } else {
      subject.pipe(
        map((s: string) => s.trim()),
        distinctUntilChanged(),
        filter((s: string) => s.length >= 2),
        debounceTime(200),
        map((value) => {
          setLoading(true);
          return value;
        }),
        delay(2000),
        switchMap(async (value: string) => {
          const index = await client.getIndex('product');
          const products = await index.search(value);
          setLoading(false);
          await router.push('/search');
          dispatch(setShopSearchState(products.hits));
        }),
        catchError((err) => of(false))
      ).subscribe(() => setLoading(false));
    }
  }, [subject]);*/

  const onSearchChange = (e) => setSearch(e.target.value);

  const validSearch = (event) => {
    router.push(`${router.pathname}${buildShopParamsGET(
      findQueryParamsValue(queries, 'sort'),
      findQueryParamsValue(queries, 'page'),
      findQueryParamsValue(queries, 'range'),
      findQueryParamsValue(queries, 'cat'),
      findQueryParamsValue(queries, 'filters'),
      search,
    )}`);

    event.stopPropagation();
  }

  return (
    <div className={styles['container'] + " rounded-lg mx-2 md:mx-0 mt-5 md:mt-0 p-4 mb-5 shadow-sm" +
      " bg-white" +
      " dark:bg-gray-800"}>
      <label htmlFor="default-search"
             className="mb-2 text-sm font-medium text-gray-900 sr-only dark:text-white">Rechercher</label>
      <div className="relative">
        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
          <svg aria-hidden="true"
               className="w-5 h-5 text-gray-500 dark:text-gray-400"
               fill="none"
               stroke="currentColor"
               viewBox="0 0 24 24"
               xmlns="http://www.w3.org/2000/svg">
            <path strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
          </svg>
        </div>
        <input type="search"
               id="default-search"
               value={search}
               onChange={onSearchChange}
               className="block w-full p-4 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
               placeholder="Rechercher un produit ..." />
        <button type="button"
                onClick={(event) => validSearch(event)}
                className="text-white absolute right-2.5 bottom-2.5 font-medium rounded-lg text-sm px-4 py-2
                                bg-blue-700
                                hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">
          <FontAwesomeIcon icon={faMagnifyingGlass} />
        </button>
      </div>
    </div>
  );
}

export default ShopSearch;
