import React, { useEffect, useRef, useState } from "react";
import style from "./productSearch.module.css";
import Loader from "./loader";
import { customerApi } from "@/api/api";
import { CancelToken } from "axios";
import {
  CheckCircleOutline,
  SearchOutlined,
  ShoppingCartOutlined,
} from "@mui/icons-material";
import { useRouter } from "next/router";
import Image from "next/image";
import NextImage from "@/other/NextImage";

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

  const router = useRouter();
  const ref = useRef();
  let timer;

  const searchProducts = async (value = "") => {
    if (!value) setSelectionOption([]);
    else {
      clearTimeout(timer);
      timer = setTimeout(async () => {
        setLoader(true);
        await customerApi
          .get("/search/products?search=" + value + "&field=name image slug", {
            cancelToken: source.token,
          })
          .then((res) => {
            if (res.data.success === true) {
              setSelectionOption(() => {
                let newArray = [];
                if (res.data.data.length > 0) {
                  for (const item of res.data.data) {
                    newArray.push({
                      title: item.name,
                      id: item._id,
                      slug: item.slug,
                      image:
                        item.image && item.image.length > 0
                          ? item.image[0]
                          : null,
                    });
                  }
                  return newArray;
                }
              });
            }
            setLoader(false);
          })
          .catch((err) => {
            console.log(err);
            setLoader(false);
          });
      }, 500);
    }
  };

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

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

  useEffect(() => {
    searchProducts(search);
    return () => clearTimeout(timer);
  }, [search]);

  return (
    <React.Fragment>
      <div
        className={`${style.search_select} ${
          props.customCss && props.customCss
        } ${props.disabled ? style.disabled : ""}`}
        id={randomID}
        ref={ref}
      >
        <input
          className={`${style.search_input} ${
            props.customCssForBtn ? props.customCssForBtn : ""
          } ${props.error ? style.error : ""}`}
          type="text"
          placeholder={`${
            props.placeholder ? props.placeholder : "Search Here"
          }`}
          id="search"
          value={search}
          onChange={(e) => {
            setSearch(e.target.value);
            setLoader(true);
          }}
          onClick={() => {
            if (!props.disabled) setOpen(true);
          }}
        />
        {/* <label htmlFor="search">
          <div className={style.search_icon}>
            <div className={style.icon_svg}>
              <SearchOutlined />
            </div>
          </div>
        </label> */}
        {open && search && (
          <>
            {selectOption && selectOption.length > 0 && (
              <ul className={style.select_list}>
                {!loader &&
                  selectOption &&
                  selectOption.length > 0 &&
                  selectOption.map((item, index) => (
                    <li
                      onClick={() => {
                        setSelectionOption([]);
                        setSearch("");
                        props.closeSearch();
                        router.push("/product/" + item.slug);
                      }}
                      key={index}
                    >
                      <div className={style.main_layout}>
                        {item.image && (
                          <div className={style.image}>
                            <NextImage
                              className={style.product_image}
                              src={
                                process.env.NEXT_PUBLIC_UPLOADS +
                                "/products/" +
                                item.image
                              }
                              alt="No Image"
                              fill
                              onError={() => {
                                setSelectionOption((prev) => {
                                  let newArray = [...prev];
                                  newArray[index].image = null;
                                  return newArray;
                                });
                              }}
                            />
                          </div>
                        )}
                        <div className={style.text}>
                          <div className={style.titleText}>
                            <p>
                              <b>{item.title}</b>
                            </p>
                          </div>
                        </div>
                      </div>
                    </li>
                  ))}
              </ul>
            )}
            {loader && (
              <ul>
                <div className={style.noData}>
                  <Loader className={style.loader} />
                </div>
              </ul>
            )}
          </>
        )}
      </div>
    </React.Fragment>
  );
};

export default ProductSearch;
