import React, { useEffect, useMemo, useRef, useState } from "react";
import style from "./filters.module.css";
import SearchSelect from "@/components/utils/searchSelect";
import { useSelector } from "react-redux";

const Filters = (props) => {
  const sortOption = [
    { title: "Newer To Older", value: "newer_to_older" },
    { title: "Older To Newer", value: "older_to_newer" },
    { title: "High Price To Low Price", value: "high_price_to_low_price" },
    { title: "Low Price To High Price", value: "low_price_to_high_price" },
  ];
  const [minPriceRange, setMinPriceRange] = useState(0);
  const [maxPriceRange, setMaxPriceRange] = useState(10000);
  const [sortBy, setSortBy] = useState();
  const [appliedData, setAppliedData] = useState();
  const [prevAppliedData, setPrevAppliedData] = useState();
  const [applyBtn, setApplyBtn] = useState(true);
  const [hideBtn, setHideBtn] = useState(true);
  const ref = useRef();

  const currencyType = useSelector((state) => state.generalStore.currency_type);
  
  useMemo(() => {
    let priceRangeLocal = localStorage.getItem("price_range");
    let sortByLocal = localStorage.getItem("sort_by");
    if (priceRangeLocal || sortByLocal) {
      setHideBtn(false);
    }
  }, []);

  useMemo(() => {
    let priceRangeLocal = localStorage.getItem("price_range");
    let sortByLocal = localStorage.getItem("sort_by");
    let priceRangeCurrent = { min: minPriceRange, max: maxPriceRange };
    if (priceRangeLocal) {
      priceRangeCurrent = JSON.parse(priceRangeLocal);
      setMinPriceRange(priceRangeCurrent.min);
      setMaxPriceRange(priceRangeCurrent.max);
    }
    let sortByCurrent = sortBy;
    if (sortByLocal) {
      sortByCurrent = sortByLocal;
      setSortBy(sortByCurrent);
    }
    setPrevAppliedData({ ...priceRangeCurrent, sortBy: sortByCurrent });
    let sortByData = "";
    if (sortByCurrent === "newer_to_older") {
      sortByData = { created_at: -1 };
    } else if (sortByCurrent === "older_to_newer") {
      sortByData = { created_at: 1 };
    } else if (sortByCurrent === "high_price_to_low_price") {
      sortByData = { price: -1 };
    } else if (sortByCurrent === "low_price_to_high_price") {
      sortByData = { price: 1 };
    }
    let priceRangeData = {
      price: {
        $lte: Number(priceRangeCurrent.max),
        $gte: Number(priceRangeCurrent.min),
      },
    };
    props.getFilterData({
      priceRangeData: priceRangeData,
      sortByData: sortByData,
    });
  }, [appliedData]);

  useMemo(() => {
    if (
      (prevAppliedData && prevAppliedData.min != minPriceRange) ||
      (prevAppliedData && prevAppliedData.max != maxPriceRange)
    ) {
      setApplyBtn(true);
    } else {
      setApplyBtn(false);
    }
    if (prevAppliedData && prevAppliedData.sortBy != sortBy) {
      setApplyBtn(true);
    } else setApplyBtn(false);
  }, [prevAppliedData]);

  function usePrevious(value) {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
  }
  const prevAmount = usePrevious({ minPriceRange, maxPriceRange });
  useMemo(() => {
    if (Number(maxPriceRange) - Number(minPriceRange) <= 0) {
      if (prevAmount.minPriceRange != minPriceRange) {
        setMinPriceRange(() => Number(maxPriceRange) - 50);
      } else if (prevAmount.maxPriceRange != maxPriceRange) {
        setMaxPriceRange(() => Number(minPriceRange) + 50);
      }
    }
    if (
      (prevAppliedData && prevAppliedData.min != minPriceRange) ||
      (prevAppliedData && prevAppliedData.max != maxPriceRange)
    ) {
      setApplyBtn(true);
      setHideBtn(false);
    } else {
      setApplyBtn(false);
    }
  }, [maxPriceRange, minPriceRange]);

  useEffect(() => {
    if (ref && ref.current) {
      ref.current.style.left = (Number(minPriceRange) / 10000) * 100 + "%";
      ref.current.style.right =
        100 - (Number(maxPriceRange) / 9999) * 100 + "%";
    }
  }, [maxPriceRange, minPriceRange, ref.current]);

  useEffect(() => {
    if (prevAppliedData.sortBy != sortBy) {
      setApplyBtn(true);
      setHideBtn(false);
    } else {
      setApplyBtn(false);
    }
  }, [sortBy]);

  return (
    <div className={style.filters}>
      <SearchSelect
        setOption={sortOption}
        placeholder="Sort By"
        getValue={(value) => {
          setSortBy(value.value);
        }}
        setValue={sortBy}
      />
      <div className={style.price_range_section}>
        <p> Price </p>
        <div className={style.price_range_text}>
          Min{" "}
          <span>
            {minPriceRange} {currencyType}
          </span>{" "}
          - Max{" "}
          <span>
            {maxPriceRange} {currencyType}
          </span>
        </div>
        <div class={style.slider}>
          <div class={style.progress} ref={ref}></div>
        </div>
        <div className={style.price_range}>
          <input
            type="range"
            class="range-min"
            min="0"
            max="10000"
            value={minPriceRange}
            step="50"
            onChange={(e) => setMinPriceRange(e.target.value)}
          />
          <input
            type="range"
            class="range-max"
            min="0"
            max="10000"
            value={maxPriceRange}
            step="50"
            onChange={(e) => setMaxPriceRange(e.target.value)}
          />
        </div>
      </div>
      {applyBtn && !hideBtn ? (
        <button
          className={`secondary-btn ${style.button}`}
          onClick={() => {
            setAppliedData({
              min: minPriceRange,
              max: maxPriceRange,
              sortBy: sortBy || "",
            });
            localStorage.setItem(
              "price_range",
              JSON.stringify({
                min: minPriceRange,
                max: maxPriceRange,
              })
            );
            setHideBtn(false);
            localStorage.setItem("sort_by", sortBy || "");
          }}
        >
          Apply
        </button>
      ) : (
        !hideBtn && (
          <button
            className={`secondary-btn ${style.button}`}
            onClick={() => {
              setAppliedData({
                min: 0,
                max: 10000,
                sortBy: "",
              });
              setPrevAppliedData({
                min: 0,
                max: 10000,
                sortBy: "",
              });
              setMinPriceRange(0);
              setMaxPriceRange(10000);
              setSortBy("");
              setHideBtn(true);
              localStorage.removeItem("sort_by");
              localStorage.removeItem("price_range");
            }}
          >
            Clear
          </button>
        )
      )}
    </div>
  );
};

export default Filters;
