import React, { useEffect, useState } from "react";
import style from "./carData.module.css";
import SearchSelect from "@/components/utils/searchSelect";
import { carCatalogApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import { useRouter } from "next/router";

const CarDataForm = (props) => {
  const [brandOptions, setBrandOptions] = useState({});
  const [brandLoader, setBrandLoader] = useState(true);
  const [menu, setMenu] = useState([]);
  const [options, setOptions] = useState({});
  const [selectedParams, setParams] = useState({});
  const [loader, setLoader] = useState(false);
  const [selectedID, setSelectedID] = useState();
  const router = useRouter();
  const pathName = router.asPath;

  const onBrandLoad = async () => {
    setBrandLoader(true);
    await carCatalogApi
      .get("/car-catalog/brands")
      .then((res) => {
        setBrandOptions(() => {
          let newArray = [];
          for (const item of res.data.result) {
            newArray.push({
              title: item.substring(0, item.length - 1),
              value: item.substring(0, item.length - 1),
            });
          }
          console.log("newArray: ", newArray);
          return newArray;
        });
        setBrandLoader(false);
      })
      .catch((err) => {
        setBrandLoader(false);
        console.log(err);
      });
  };

  const onMenuLoad = async () => {
    setLoader(true);
    const params = JSON.stringify(selectedParams);
    await carCatalogApi
      .get(
        "/car-catalog/form?params=" +
          params +
          "&limit=1&page=1&field=-brand -created_at -updated_at -__v"
      )
      .then((res) => {
        console.log("res.data: ", res.data);
        if (
          res.data.result &&
          res.data.result.data &&
          res.data.result.data.menu.length > 0
        ) {
          setOptions((prev) => {
            let newObject = { ...prev };
            newObject[res.data.result.data.key] = [];
            for (const item of res.data.result.data.menu) {
              newObject[res.data.result.data.key].push({
                title: item,
                value: item,
              });
            }
            return newObject;
          });
        }

        if (res.data.result.id) {
          setSelectedID(res.data.result.id);
          props.onSelectedData && props.onSelectedData(selectedParams);
        }
        setLoader(false);
      })
      .catch((err) => {
        setLoader(false);
        console.log(err);
      });
  };

  useEffect(() => {
    console.log("options:", options);
    console.log("Object.keys(options): ", Object.keys(options));
  }, [options]);

  useEffect(() => {
    onBrandLoad();
  }, []);

  useEffect(() => {
    onMenuLoad();
  }, [selectedParams]);

  return (
    <React.Fragment>
      <div className={style.search_form}>
        <p className={style.search_head}>Select Car</p>
        <div className={style.search_form_section}>
          <SearchSelect
            placeholder=" Brand"
            customCssForBtn={style.customSearchSelect}
            getValue={(value) => {
              setSelectedID(null);
              setParams(() => {
                let newObject = {};
                newObject["brand"] = value.value;
                return newObject;
              });
              setOptions({});
            }}
            setOption={brandOptions}
            loader={brandLoader}
          />
          {Object.keys(options).map(
            (item) =>
              options[item].length > 0 && (
                <SearchSelect
                  key={item}
                  placeholder={
                    "Select " + item.toUpperCase().replace(/_/g, " ")
                  }
                  customCssForBtn={style.customSearchSelect}
                  setOption={options[item]}
                  getValue={(value) => {
                    setSelectedID(null);
                    setParams((prev) => {
                      let newObject = { ...prev };
                      newObject[item] = value.value;
                      return newObject;
                    });
                    if (Object.keys(options).length > 0) {
                      let itemFound = false;
                      for (const loopItem in options) {
                        if (loopItem == item) {
                          itemFound = true;
                          continue;
                        }
                        console.log("itemFound: ", itemFound);
                        if (itemFound === true) {
                          console.log("loopItem: ", loopItem);
                          setOptions((prev) => {
                            let newObject = { ...prev };
                            newObject[loopItem] = [];
                            return newObject;
                          });
                          setParams((prev) => {
                            let newObject = { ...prev };
                            delete newObject[loopItem];
                            return newObject;
                          });
                        }
                      }
                    }
                  }}
                />
              )
          )}
          {loader && selectedParams.brand && (
            <Loader className={style.customLoader} />
          )}
        </div>
      </div>
    </React.Fragment>
  );
};

export default CarDataForm;
