import React, { useEffect, useState } from "react";
import OverlayBox from "../utils/others/overlayBox";
import style from "./categories.module.css";
import InputText from "../utils/inputText";
import SearchForm from "./searchForm";
import { KeyboardArrowDown, KeyboardArrowUp } from "@mui/icons-material";
import { carCatalogApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import { useRouter } from "next/router";
import { useSelector } from "react-redux";

const ProductFilter = () => {
  const router = useRouter();
  const category = useSelector((state) => state.categoryStore.category);
  const loader = useSelector((state) => state.categoryStore.loader);
  const [selectedID, setSelectedID] = useState("all");
  let pathName = router.asPath;
  const { query } = router;

  const formatURL = (pathName) => {
    pathName = pathName.split("/");
    console.log("pathName: ", pathName);
    for (const index in pathName) {
      if (pathName[index].includes("category[")) {
        pathName.splice(index, 1);
      }
    }
    pathName = pathName.join("/");
    return pathName;
  };

  const removeCar = (pathName) => {
    pathName = pathName.split("/");
    console.log("pathName: ", pathName);
    for (const index in pathName) {
      if (pathName[index].includes("car[")) {
        pathName.splice(index, 1);
      }
    }
    pathName = pathName.join("/");
    return pathName;
  };

  useEffect(() => {
    if (query.slug) {
      if (query.slug && query.slug.length > 0) {
        console.log("query.slug: ", query.slug);
        for (const item of query.slug) {
          if (item.includes("car[")) {
            setCarBrand(item.split(" ")[1]);
            let data = item.split("[")[1];
            data = data.split("]")[0];
            setCarID(data);
          }
        }
      }
    }
  }, [query]);

  const [categorySelected, setCategorySelected] = useState([]);

  const CategoryRecursion = (props) => {
    return props.item.child.map((item, index) => (
      <ul key={`${item.name}_${index}`} className={style.child_category}>
        <li>
          <p
            className={`${style.selectBtn} ${
              selectedID == item._id ? style.selected : ""
            }`}
          >
            <span
              onClick={() => {
                setSelectedID(item._id);
                router.replace(
                  formatURL(pathName) +
                    "/" +
                    "category[" +
                    item._id +
                    "]_" +
                    item.name,
                  undefined,
                  {
                    shallow: true,
                  }
                );
              }}
            >
              {item.name}
            </span>
            {item.type === "group" &&
              (categorySelected[item._id] ? (
                <KeyboardArrowUp
                  onClick={() =>
                    setCategorySelected((prev) => {
                      let newObject = { ...prev };
                      newObject[item._id] = !newObject[item._id];
                      return newObject;
                    })
                  }
                />
              ) : (
                <KeyboardArrowDown
                  onClick={() =>
                    setCategorySelected((prev) => {
                      let newObject = { ...prev };
                      newObject[item._id] = !newObject[item._id];
                      return newObject;
                    })
                  }
                />
              ))}
          </p>
          {categorySelected[item._id] && <CategoryRecursion item={item} />}
        </li>
      </ul>
    ));
  };

  useEffect(() => {
    if (router.asPath.includes("category["))
      setSelectedID(router.asPath.split("category[")[1].split("]")[0]);
  }, []);

  return (
    <div className={style.filter}>
      <div className={style.category_select_filter}>
        <div className={style.category_select_title}>Category</div>
        {loader ? (
          <Loader className={style.loader} />
        ) : (
          <>
            <ul className={style.parentUl}>
              <li>
                <p
                  className={`${style.selectBtn} ${
                    selectedID == "all" ? style.selected : ""
                  }`}
                  onClick={() => {
                    setSelectedID("all");

                    router.replace(formatURL(pathName), undefined, {
                      shallow: true,
                    });
                  }}
                >
                  {" "}
                  All
                </p>
              </li>
            </ul>
            {category.map((item, index) => (
              <ul key={`${item.name}_${index}`} className={style.parentUl}>
                <li>
                  <p
                    className={`${style.selectBtn} ${
                      selectedID == item._id ? style.selected : ""
                    }`}
                  >
                    <span
                      onClick={() => {
                        setSelectedID(item._id);
                        router.replace(
                          formatURL(pathName) +
                            "/" +
                            "category[" +
                            item._id +
                            "]_" +
                            item.name,
                          undefined,
                          {
                            shallow: true,
                          }
                        );
                      }}
                    >
                      {item.name}
                    </span>
                    {item.type === "group" &&
                      (categorySelected[item._id] ? (
                        <KeyboardArrowUp
                          onClick={() =>
                            setCategorySelected((prev) => {
                              let newObject = { ...prev };
                              newObject[item._id] = !newObject[item._id];
                              return newObject;
                            })
                          }
                        />
                      ) : (
                        <KeyboardArrowDown
                          onClick={() =>
                            setCategorySelected((prev) => {
                              let newObject = { ...prev };
                              newObject[item._id] = !newObject[item._id];
                              return newObject;
                            })
                          }
                        />
                      ))}
                  </p>
                  {categorySelected[item._id] && (
                    <CategoryRecursion item={item} />
                  )}
                </li>
              </ul>
            ))}
          </>
        )}
        {!loader && category.length == 0 && (
          <p className="exist_error">Not Available</p>
        )}
      </div>
    </div>
  );
};

export default ProductFilter;
