"use client";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { useFilter } from "@/stores/productsFilter";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { IoSearchOutline } from "react-icons/io5";
import PriceSlider from "./PriceSlider";
import { useState } from "react";

export default function Filter({
  filters,
  subCategories,
  setIsFilteredLoading,
}) {
  const router = useRouter();
  const [checkedSubCategoryId, setCheckedSubCategoryId] = useState(null);
  const { brands, size, labels, values } = filters;
  const prices = ["0-99", "100-400", "301-600", "501-800", "801-1000", "1000+"];
  const t = useTranslations("filter");
  const {
    filters: filterState,
    toggleSize,
    toggleBrand,
    toggleLabel,
    setPriceRange,
    setSearch,
  } = useFilter();

  // State to control alert visibility
  const handlePriceChange = (minPrice, maxPrice) => {
    setPriceRange(minPrice, maxPrice);
  };

  // Handle search input change
  const handleSearchChange = (e) => {
    const value = e.target.value;
    setSearch(value);
  };

  return (
    <div className="space-y-6">
      <div className="">
        <div className="relative">
          <input
            type="search"
            placeholder={t("search")}
            className="w-full p-1 ps-6 focus:ring-0 focus:outline-none border border-gray-400 rounded-md placeholder:text-gray-400 focus:border-black focus:border-2"
            value={filterState.search}
            onChange={handleSearchChange}
          />
          <IoSearchOutline className="absolute start-1 top-1/2 -translate-y-1/2 font-bold" />
        </div>
      </div>

      <Accordion type="multiple" className="space-y-3">
        {/* subCategories */}

        {Array.isArray(subCategories) && subCategories.length > 0 && (
          <AccordionItem value="sub-categories">
            <AccordionTrigger className="font-semibold">
              {t("subCategories")}
            </AccordionTrigger>
            <AccordionContent>
              <div className="max-h-44 overflow-y-auto flex items-start gap-2 flex-col py-5">
                {subCategories?.map((item, ind) => (
                  <div className="flex items-center gap-2" key={item.id}>
                    <input
                      id={ind}
                      type="radio"
                      checked={item.id === checkedSubCategoryId}
                      onChange={() => {
                        setIsFilteredLoading(true);
                        setCheckedSubCategoryId(item.id);
                        router.push(`/products/filter/${item.id}`);
                      }}
                    />

                    <label
                      htmlFor={ind}
                      className="text-[#2E2E2E] font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      {item.title}
                    </label>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        )}

        {/* Product size */}
        {size.length > 0 && (
          <AccordionItem value="product-type">
            <AccordionTrigger className="font-semibold">
              {t("size")}
            </AccordionTrigger>
            <AccordionContent>
              <div className="max-h-44 overflow-y-auto flex items-start gap-2 flex-col">
                {Object.values(size).map((item, ind) => (
                  <div key={ind} className="flex items-center gap-2">
                    <input
                      id={ind}
                      type="checkbox"
                      checked={filterState.size.includes(item.id)}
                      onChange={() => toggleSize(item.id)}
                    />
                    <label
                      htmlFor={ind}
                      className="text-[#2E2E2E] font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      {item.title}
                    </label>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        )}

        {/* Brands */}
        {brands && (
          <AccordionItem value="brands">
            <AccordionTrigger className="font-semibold">
              {t("brands")}
            </AccordionTrigger>
            <AccordionContent>
              <div className="max-h-44 overflow-y-auto flex items-start gap-2 flex-col">
                {brands.map((brand, index) => (
                  <div key={index} className="flex items-center gap-2">
                    <input
                      type="checkbox"
                      id={brand?.data?.name}
                      checked={filterState.brand.includes(
                        brand?.data?.brand_id
                      )}
                      onChange={() => toggleBrand(brand?.data?.brand_id)}
                    />
                    <label
                      htmlFor={brand?.data?.name}
                      className="text-[#2E2E2E] font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      {brand?.data?.name}
                    </label>
                  </div>
                ))}
              </div>
            </AccordionContent>
          </AccordionItem>
        )}

        {/* Labels and Values */}
        {labels && (
          <div>
            {labels.map((label) => (
              <AccordionItem key={label.id} value={`label-${label.id}`}>
                <AccordionTrigger className="font-semibold">
                  {label.title}
                </AccordionTrigger>
                <AccordionContent>
                  <div className="max-h-44 overflow-y-auto flex items-start gap-2 flex-col">
                    {values
                      .filter((value) => value.lable_id === label.lable_id)
                      .map((value) => (
                        <div key={value.id} className="flex items-center gap-2">
                          <input
                            type="checkbox"
                            id={value.id}
                            checked={filterState.label.includes(value.value)}
                            onChange={() => toggleLabel(value.value)}
                          />
                          <label
                            htmlFor={value.id}
                            className="text-[#2E2E2E] font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                          >
                            {value.value}
                          </label>
                        </div>
                      ))}
                  </div>
                </AccordionContent>
              </AccordionItem>
            ))}
          </div>
        )}

        {/* Prices */}
        <AccordionItem value="prices">
          <AccordionTrigger className="font-semibold flex">
            {t("price")}
          </AccordionTrigger>
          <AccordionContent>
            <PriceSlider onChange={handlePriceChange} />
            {prices.map((price, index) => {
              const [min, max] = price.split("-").map(Number);
              return (
                <div key={index} className="flex items-center gap-2 my-2">
                  <input
                    id={`price-${price}`}
                    type="radio"
                    className="p-10"
                    checked={
                      filterState.min_price === min &&
                      filterState.max_price === max
                    }
                    onChange={() => setPriceRange(min, max)}
                  />
                  <label
                    htmlFor={`price-${price}`}
                    className="text-[#2E2E2E] font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    {`${min} - ${max}`}
                  </label>
                </div>
              );
            })}
          </AccordionContent>
        </AccordionItem>
      </Accordion>
    </div>
  );
}
