/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useState } from "react";
import LayoutCard from "./LayoutCard";
import SortButton from "./SortButton";
import SearchIcon from "../icons/SearchIcon";
import Button from "../Button";
import FilterIcon from "../icons/FilterIcon";
import useModal from "../../store/useModal";
import { MobileModalWrapper } from "../modals/mobile/MobileModalWrapper";
import SearchFiltersModal from "../modals/mobile/SearchFiltersModal";
import { updateAccessToken } from "../../api/updateAccessToken";
import useApartments from "../../store/useApartments";
import useSearchFilters from "../../store/useSearchFilters";
import { useDebounce } from "@uidotdev/usehooks";
import {
  perPageInitial,
  pageInitial,
} from "../../consts/initialMasterplanFilters";
import { getFilteredApartments } from "../../calc/getFilteredApartments";
import SearchLoader from "./SearchLoader";

const LayoutOptions = () => {
  const { apartments, setApartments } = useApartments();
  const [isLoading, setIsLoading] = useState(false);

  const { setModal } = useModal();
  const {
    roveHomeTypeCheckboxes,
    apartmentTypeCheckboxes,
    multirangeSliders,
    viewCheckboxes,
    switchers,
    sortList,
    setSortList,
    page,
    setPage,
    setPerPage,
    perPage,
  } = useSearchFilters();
  const debouncedSliders = useDebounce(multirangeSliders, 300);

  const handleOnSortClick = (sortId: string) => {
    const updatedSortList = sortList.map((sort) => {
      const isSelected = sort.id === sortId;
      return { ...sort, isSelected: isSelected };
    });
    setSortList(updatedSortList);
  };

  const handleOnFilterClick = () => {
    setModal(
      <MobileModalWrapper>
        <SearchFiltersModal />
      </MobileModalWrapper>
    );
  };

  function handleOnShowMoreBtnClick(): void {
    const _page = page + 1;
    const _perPage = _page * perPageInitial;

    setPage(_page);
    setPerPage(_perPage);
  }

  useEffect(() => {
    const zohoToken = localStorage.getItem("ACCESS_TOKEN");
    setIsLoading(true);

    updateAccessToken()
      .then((token) => {
        if (token) {
          getFilteredApartments(
            token,
            setApartments,
            roveHomeTypeCheckboxes,
            apartmentTypeCheckboxes,
            debouncedSliders,
            switchers,
            viewCheckboxes,
            sortList,
            pageInitial,
            perPage
          );
        }
      })
      .then(() =>
        getFilteredApartments(
          zohoToken,
          setApartments,
          roveHomeTypeCheckboxes,
          apartmentTypeCheckboxes,
          debouncedSliders,
          switchers,
          viewCheckboxes,
          sortList,
          pageInitial,
          perPage
        )
      )
      .finally(() => {
        setIsLoading(false);
      });

    // getFilteredApartments(
    //   zohoToken,
    //   setApartments,
    //   roveHomeTypeCheckboxes,
    //   apartmentTypeCheckboxes,
    //   debouncedSliders,
    //   switchers,
    //   viewCheckboxes,
    //   sortList,
    //   pageInitial,
    //   perPage
    // )
    //   .catch((error) => {
    //     const errorStatus = error.response.status;

    //     if (errorStatus === 401) {
    //       updateAccessToken().then((token) => {
    //         if (token) {
    //           getFilteredApartments(
    //             token,
    //             setApartments,
    //             roveHomeTypeCheckboxes,
    //             apartmentTypeCheckboxes,
    //             debouncedSliders,
    //             switchers,
    //             viewCheckboxes,
    //             sortList,
    //             pageInitial,
    //             perPage
    //           );
    //         }
    //       });
    //     }
    //   })
    //   .finally(() => {
    //     setIsLoading(false);
    //   });
  }, [
    setApartments,
    roveHomeTypeCheckboxes,
    apartmentTypeCheckboxes,
    debouncedSliders,
    switchers,
    viewCheckboxes,
    sortList,
    perPage,
  ]);

  return (
    <section className="w-full p-6 flex flex-col">
      <div className="flex justify-between items-center border-b">
        <div className="flex w-full justify-between pb-4 lg:flex-row lg:items-center flex-col">
          <div className="flex gap-4 font-semibold text-subheadline-s leading-7 py-[6px]">
            <h2 className="text-[#0D1922]">Units</h2>
            <p className="text-[#73787C]">
              {apartments ? apartments.length : 0}
            </p>
          </div>
          <SortButton sortList={sortList} onClick={handleOnSortClick} />
        </div>
        <div className="lg:hidden block">
          <Button
            icon={<FilterIcon />}
            text="Filters"
            className="text-[#0D1922B2]"
            onClick={handleOnFilterClick}
          />
        </div>
      </div>
      {isLoading ? (
        <SearchLoader />
      ) : (
        <div className="grid 2xl:grid-cols-4 xl:grid-cols-3 grid-cols-2 gap-4 pt-6">
          {apartments &&
            apartments.map((apartment) => (
              <LayoutCard apartmentCard={apartment} key={apartment.id} />
            ))}
        </div>
      )}
      <div
        className="bg-white rounded-lg mt-4 py-[10px] flex justify-center select-none cursor-pointer items-center gap-2"
        onClick={handleOnShowMoreBtnClick}
      >
        <SearchIcon /> Show 12 more apartments
      </div>
    </section>
  );
};

export default LayoutOptions;
