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

const SearchMultiSelect = (props) => {
  const [selectOption, setSelectionOption] = useState([]);

  const [selected, setSelected] = useState([]);
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [loader, setLoader] = useState(false);
  const [sendSelected, setSendSelected] = useState(null);
  const [randomID] = useState("id_" + Math.floor(Math.random() * 1000000 + 1));

  const isSelected = (value) => {
    for (const item of selected) {
      if (item.value === value) return true;
    }
    return false;
  };

  const onSelect = (selectedItem) => {
    let isAlreadyExist = false;
    selected.map((item, index) => {
      if (item.value === selectedItem.value) {
        setSelected((prev) => {
          let newArray = [...prev];
          newArray.splice(index, 1);
          return newArray;
        });
        setSendSelected((prev) => {
          let newArray = [...selected];
          newArray.splice(index, 1);
          return newArray;
        });
        isAlreadyExist = true;
      }
    });
    if (isAlreadyExist === false) {
      setSelected((prev) => {
        let newArray = [...prev];
        newArray.push({ ...selectedItem });
        return newArray;
      });
      setSendSelected((prev) => {
        let newArray = [...selected];
        newArray.push({ ...selectedItem });
        return newArray;
      });
    }
  };

  const dataFilter = (data) => {
    if (data.length > 0 && data[0].title)
      return data.filter((item) => {
        return item.title.toLowerCase().includes(search.toLowerCase());
      });
    else return [];
  };

  useEffect(() => {
    console.log("sdfsf", props.setValue);
    props.setValue &&
      props.setValue.length > 0 &&
      setSelected(() => {
        let selectedValue = [];
        for (const setItem of props.setValue) {
          selectOption.map((item) => {
            if (
              item.value &&
              setItem.value.toLowerCase() === item.value.toLowerCase()
            ) {
              selectedValue.push(item);
            }
          });
        }
        return selectedValue;
      });
    console.log(selected);
  }, [props.setValue, selectOption]);

  useEffect(() => {
    props.setOption && setSelectionOption(props.setOption);

    console.log("props.setOption: ", props.setOption);
  }, [props.setOption]);

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

  useEffect(() => {
    const clickListener = (e) => {
      if (
        document.getElementsByClassName(randomID) &&
        !document.getElementById(randomID).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}
      >
        <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.length > 0 ? (
            <div className={style.selected_data_section}>
              {selected.map((item, index) => (
                <>
                  <div className={style.selected_data} key={index}>
                    <div className={style.selected_data_item}>
                      <p>{item.title}</p>
                      <span
                        onClick={() => {
                          console.log("yes");
                          onSelect(item);
                        }}
                      >
                        <FontAwesomeIcon icon={faClose} />
                      </span>
                    </div>
                  </div>
                </>
              ))}
            </div>
          ) : (
            props.placeholder || "Select Menu"
          )}
        </div>
        {open && (
          <ul className={style.select_list}>
            <div className={style.select_search}>
              <input
                type="text"
                placeholder="Search Here"
                value={search}
                onInput={(e) => setSearch(e.target.value)}
              />
            </div>
            {selectOption.length > 0 &&
              dataFilter(selectOption).map((item, index) => (
                <li
                  className={`${isSelected(item.value) && style.selected}`}
                  onClick={() => onSelect(item)}
                  key={index}
                >
                  {isSelected(item.value) && (
                    <FontAwesomeIcon icon={faCheckCircle} />
                  )}
                  {item && item.title}
                </li>
              ))}
            {props.loader && (
              <div className={style.noData}>
                <Loader className={style.loader} />
              </div>
            )}
            {!props.loader && dataFilter(selectOption).length === 0 && (
              <div className={style.noData}>No data available</div>
            )}
          </ul>
        )}
      </div>
    </React.Fragment>
  );
};

export default SearchMultiSelect;
