"use client";
import AppContext from "@ctx/AppContext";
import { Switch } from "@headlessui/react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import PersianNumber from "plugins/PersianNumber";
import RangeSlider from "plugins/RangeSlider/page";
import { useContext, useEffect, useRef } from "react";

const FilterCategory = ({
  id,
  selectedBrands,
  isChecked,
  rangePrice,
  sortBy,
  isRangePrice,
  theme,
  specialOffer,
  filter,
}) => {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const CTX = useContext(AppContext);
  const brands = CTX.state.brands;
  const pageGetProducts = CTX.state.pageGetProducts;
  const isFirstRender = useRef(true);

  const router = useRouter();

  const handleCheckboxChange = () => {
    // CTX.setIsChecked(!isChecked);
    const params = new URLSearchParams(searchParams.toString());
    if (!isChecked) {
      params.set("isActive", Number(!isChecked));
    } else {
      params.delete("isActive");
    }
    params.set("page", "0");
    router.push(`${pathname}?${params}`);
  };

  const handleSpecialOfferChange = () => {
    // CTX.setIsChecked(!isChecked);
    const params = new URLSearchParams(searchParams.toString());
    if (!specialOffer) {
      params.set("specialOffer", Number(!specialOffer));
    } else {
      params.delete("specialOffer");
    }
    params.set("page", "0");
    router.push(`${pathname}?${params}`);
  };

  const handleRangeChange = (values) => {
    // CTX.setIsRangePrice(true);

    // CTX.setRangePrice(values);
    //

    const params = new URLSearchParams(searchParams.toString());
    params.set("minPrice", values[0]);
    params.set("maxPrice", values[1]);
    params.set("page", "0");
    router.push(`${pathname}?${params}`, { scroll: false });
  };

  const handleFilterBrand = (name, id) => {
    const params = new URLSearchParams(searchParams.toString());
    let brandIds = params.get("brandIds")
      ? Array.from(params.get("brandIds").split(",") ?? [])
      : [];
    //
    if (brandIds.includes(id)) {
      brandIds = brandIds.filter((brandId) => brandId !== id);

      if (brandIds.length === 0) {
        params.delete("brandIds");
        router.push(`${pathname}?${params}`);
        return;
      }
    } else {
      brandIds.push(id);
    }
    params.set("brandIds", brandIds.join(","));
    params.set("page", "0");

    router.push(`${pathname}?${params}`);
    // Check if the brand is already selected
    // const isBrandSelected = selectedBrands.some((brand) => brand.id === id);

    // if (!isBrandSelected) {
    //   // If the brand is not already selected, add it to the state
    //   CTX.setSelectedBrands((prevBrands) => [...prevBrands, { name, id }]);
    // } else {
    //   // If the brand is already selected, remove it from the state
    //   CTX.setSelectedBrands((prevBrands) =>
    //     prevBrands.filter((brand) => brand.id !== id)
    //   );
    // }
  };

  const handleRangePriceFilter = () => {
    CTX.fetchProducts(
      0,
      id[0],
      selectedBrands,
      isChecked,
      rangePrice[0],
      rangePrice[1],
      sortBy != -1 ? sortBy : "",
      isRangePrice
    );
  };

  // useEffect(() => {
  //   if (isFirstRender.current) {
  //     isFirstRender.current = false;
  //     return;
  //   }

  //   CTX.fetchProducts(
  //     0,
  //     id[0] != 0 ? id[0] : "",
  //     selectedBrands,
  //     isChecked,
  //     rangePrice[0],
  //     rangePrice[1],
  //     sortBy != -1 ? sortBy : "",
  //     isRangePrice
  //   );
  // }, [CTX.state.selectedBrands, CTX.state.isChecked]);

  // useEffect(() => {
  //   CTX.setRangePrice([
  //     filter?.price?.minimumValue,
  //     filter?.price?.maximumValue,
  //   ]);
  // }, [filter]);

  return (
    <div
      className={` rtl  ${
        theme == 2 ? "col-span-full" : "lg:col-span-2 xl:col-span-1 ml-4"
      }`}
    >
      <div className="sticky top-20  ...">
        <div className=" w-full">
          <div
            className={` border-gray-300 rounded-lg  ${
              theme == 2 ? "bg-gray-100" : "bg-gray-50"
            } `}
          >
            <div className=" p-5 flex justify-between">
              <p className="mb-0 lg:text-sm xl:text-base">برند</p>
              <div>
                <svg
                  width="15"
                  height="15"
                  viewBox="0 0 151 89"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  className="mt-1"
                >
                  <path
                    d="M13.1436 14.2219L76.3596 75.9976L138.135 12.7815"
                    stroke="black"
                    stroke-width="25"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
              </div>
            </div>

            <div className="h-[300px] overflow-y-auto p-5 scroll-1 overflow-hidden">
              {brands?.map((e, index) => (
                <div
                  key={index}
                  onClick={() => handleFilterBrand(e.persianName, e.id)}
                >
                  <div className="flex my-2 cursor-pointer">
                    <div
                      className={` w-[30px] h-[30px] rounded-lg border ml-3 tr03 ${
                        selectedBrands.find((id) => id == e.id)
                          ? "bg-primary-200 p-1"
                          : ""
                      } `}
                    ></div>
                    <p className="mb-0 text-gray-600 text-sm mt-1">
                      {e.persianName}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div
            className={`p-5 border-gray-300 rounded-lg mt-3 flex justify-between  ${
              theme == 2 ? "bg-gray-100" : "bg-gray-50"
            } `}
          >
            <p className="mb-0 lg:text-sm xl:text-base">فقط محصولات موجود </p>
            <Switch
              checked={Boolean(Number(searchParams.get("isActive")))}
              onChange={handleCheckboxChange}
              className={`${
                isChecked ? "bg-primary-500" : "bg-gray-400"
              } relative inline-flex h-6 w-[50px] items-center rounded-full`}
            >
              <span className="sr-only">Enable notifications</span>
              <span
                className={`${
                  isChecked ? "translate-x-[-5px]" : "translate-x-[-30px]"
                } inline-block h-4 w-4 transform rounded-full bg-white transition`}
              />
            </Switch>
          </div>

          <div
            className={`p-5 border-gray-300 rounded-lg mt-3 flex justify-between  ${
              theme == 2 ? "bg-gray-100" : "bg-gray-50"
            } `}
          >
            <p className="mb-0 lg:text-sm xl:text-base">
              فقط پیشنهاد های ویژه{" "}
            </p>
            <Switch
              checked={Boolean(Number(searchParams.get("specialOffer")))}
              onChange={handleSpecialOfferChange}
              className={`${
                specialOffer ? "bg-primary-500" : "bg-gray-400"
              } relative inline-flex h-6 w-[50px] items-center rounded-full`}
            >
              <span className="sr-only">Enable notifications</span>
              <span
                className={`${
                  specialOffer ? "translate-x-[-5px]" : "translate-x-[-30px]"
                } inline-block h-4 w-4 transform rounded-full bg-white transition`}
              />
            </Switch>
          </div>

          {/* <div
            className={` p-5  border-gray-300 rounded-lg mt-3  ${
              theme == 2 ? "bg-gray-100" : "bg-gray-50"
            } `}
          >
            <div className="flex justify-between ">
              <p className="mb-0">محدوده قیمت</p>
              <div>
                <svg
                  width="15"
                  height="15"
                  viewBox="0 0 151 89"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  className="mt-1"
                >
                  <path
                    d="M13.1436 14.2219L76.3596 75.9976L138.135 12.7815"
                    stroke="black"
                    stroke-width="25"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
              </div>
            </div>
            <div className="mt-10 px-5">
              <RangeSlider
                values={rangePrice}
                min={filter?.price?.minimumValue}
                max={filter?.price?.maximumValue}
                onChange={(e) => handleRangeChange(e)}
              />
            </div>

            <div className="flex mt-5">
              <div className="w-full text-center">
                <p className="mb-0 text-sm">تا قیمت</p>
                <p className="mb-0">
                  <PersianNumber number={rangePrice[0]} style="font-bold" />
                </p>
              </div>
              <div className="w-full text-center">
                <p className="mb-0 text-sm">از قیمت</p>
                <p className="mb-0">
                  <PersianNumber number={rangePrice[1]} style="font-bold" />
                </p>
              </div>
            </div>
          </div> */}
        </div>
      </div>
    </div>
  );
};

export default FilterCategory;
