import React, { useEffect, useRef, useState } from "react";
import style from "./searchApiSelect.module.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCheckCircle } from "@fortawesome/free-solid-svg-icons";
import Loader from "./loader";

const SearchApiSelect = (props) => {
  const [selectOption, setSelectionOption] = useState([]);
  const ref = useRef();
  const [loader, setLoader] = useState(false);
  const [selected, setSelected] = useState({});
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [sendSelected, setSendSelected] = useState();
  const [randomID] = useState("id_" + Math.floor(Math.random() * 1000000 + 1));

  const onSelect = (item) => {
    setSelected({ ...item });
    setSendSelected({ ...item });
    setOpen((prev) => !prev);
  };

  useEffect(() => {
    console.log("sdfsf", props.setValue);
    props.setValue &&
      setSelected({ title: props.setValue, value: props.setValue });
  }, [props.setValue, selectOption]);

  useEffect(() => {
    setSelectionOption(props.setOption);
    setLoader(false);
    console.log("props.setOption: ", props.setOption);
  }, [props.setOption]);

  useEffect(() => {
    if (sendSelected) props.getValue && props.getValue(sendSelected);
  }, [sendSelected]);

  useEffect(() => {
    const clickListener = (e) => {
      if (
        document.getElementsByClassName(randomID) &&
        !ref.current.contains(e.target)
      ) {
        setOpen(false);
      }
    };

    window.addEventListener("click", clickListener);

    return () => {
      window.removeEventListener("click", clickListener);
    };
  }, []);

  return (
    <React.Fragment>
      <div
        className={`${style.search_select} ${
          props.customCss && props.customCss
        } ${props.disabled ? style.disabled : ""}`}
        id={randomID}
        ref={ref}
      >
        <div
          className={`${style.search_btn} ${
            props.customCssForBtn ? props.customCssForBtn : ""
          } ${props.error ? style.error : ""}`}
          onClick={() => {
            if (!props.disabled) setOpen((prev) => !prev);
          }}
        >
          <div className={style.overlay} />
          {selected.title || props.placeholder || "Select Menu"}
        </div>
        {open && (
          <ul className={style.select_list}>
            <div className={style.select_search}>
              <input
                type="text"
                placeholder={`${
                  props.setSearchPlaceholder
                    ? props.setSearchPlaceholder
                    : "Search Here"
                }`}
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setLoader(true);
                  props.searchData(e.target.value);
                }}
              />
            </div>
            {!loader &&
              selectOption.length > 0 &&
              selectOption.map((item, index) => (
                <li
                  className={`${
                    selected.value === item.value && style.selected
                  }`}
                  onClick={() => onSelect(item)}
                  key={index}
                >
                  {selected.title === item.title &&
                    selected.value === item.value && (
                      <FontAwesomeIcon icon={faCheckCircle} />
                    )}
                  {item && item.title}
                </li>
              ))}
            {loader && (
              <div className={style.noData}>
                <Loader className={style.loader} />
              </div>
            )}
          </ul>
        )}
      </div>
    </React.Fragment>
  );
};

export default SearchApiSelect;
