import React from "react";
import Disclosure from "components/Disclosure";
import AppiledFilters from "./AppiledFilters";
import SearchFilterBar from "./SearchFilterBar";
import axios from "axios";
import { useDebounce } from "./functions/debounce";
import { IProduct } from "./IProdutct";
import { useTranslation } from "react-i18next";

type Props = {
  className?: string;
};

export default function Fiter({ className }: Props) {
  const [checkedId, setCheckedId] = React.useState<Array<number>>([]);
  const [activeFilter, setActiveFilter] = React.useState<Array<IProduct>>([]);

  /* -------------------------------------------------------------------------- */
  /*      Test request to demonstrate the basic functionality of the filter     */
  /* -------------------------------------------------------------------------- */

  const [query, setQuery] = React.useState("");
  const [hints, setHints] = React.useState<Array<IProduct>>([]);

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setQuery(e.target.value);
  };
  const debounced = useDebounce(query);

  const [t, i18next] = useTranslation();

  async function fetchProducts() {
    const response = await axios.get(
      `https://dummyjson.com/products/search?q=${debounced}`
    );
    setHints(response.data.products);
  }
  React.useEffect(() => {
    fetchProducts();
  }, [debounced, query]);

  const isChecked = (item: number) => (checkedId.includes(item) ? true : false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedId = parseInt(e.target.value);

    /* -------------  Check if "checkedId" contains "selectedIds" ------------- */
    /* -------------- If true, this checkbox is already checked -------------- */

    if (checkedId.includes(selectedId)) {
      setCheckedId(checkedId.filter((id) => id !== selectedId));
      setActiveFilter(activeFilter.filter((item) => item.id !== selectedId));
    } else {
      const newId = [...checkedId];
      newId.push(selectedId);
      setCheckedId(newId);

      /* ---------------  Adding checked filters to AppliedFilters component -------------- */

      hints.forEach((hint) => {
        if (hint.id === selectedId)
          activeFilter.push({ id: selectedId, brand: hint.brand });
        setActiveFilter(activeFilter);
      });
    }
  };

  /* ------------- Delete filter from AppliedFilters component ------------- */

  const DelFilter = (e: IProduct) => {
    setActiveFilter(activeFilter.filter((item) => item.id !== e.id));
    setCheckedId(checkedId.filter((id) => id !== e.id));
  };
  const clearAll = () => {
    setActiveFilter([]);
    setCheckedId([]);
    setQuery("");
  };
  //console.log(activeFilter)
  return (
    <>
      <div className="pl-2">
        <div className="max-w-[268px] mx-auto divide-y divide-solid">
          <AppiledFilters
            hints={activeFilter}
            delFilter={DelFilter}
            clearAll={clearAll}
          ></AppiledFilters>
          <Disclosure caption={t("filters.authors")}>
            <SearchFilterBar
              hints={hints}
              isChecked={isChecked}
              handleChange={handleChange}
              onChange={onChange}
              query={query}
              placeHolder={t("filters.enterAuthorsName")}
            />
          </Disclosure>
          <Disclosure caption={t("filters.publicationsType")}>
            <p>{t("filters.content")}</p>
          </Disclosure>
          <Disclosure caption={t("filters.publisher")}>
            <p>{t("filters.content")}</p>
          </Disclosure>
          <Disclosure caption={t("filters.publicationTopic")}>
            <p>{t("filters.content")}</p>
          </Disclosure>
        </div>
      </div>
    </>
  );
}
