"use client";
import {
  Disclosure,
  DisclosureButton,
  DisclosurePanel,
} from "@headlessui/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";

interface Option {
  value: string;
  label: string;
  checked: boolean;
}

interface ProductFilter {
  id: string;
  name: string;
  options: Option[];
}

interface FilterBoxProps {
  closeSidebar: () => void;
  filterData: ProductFilter[];
}

export default function FilterBox({
  closeSidebar,
  filterData,
}: FilterBoxProps) {
  const router = useRouter();
  const searchParams = useSearchParams();

  // ✅ Initialize local state from URL only once
  const getInitialFilters = () => {
    const obj: Record<string, string[]> = {};
    searchParams.forEach((value, key) => {
      obj[key] = value.split(",");
    });
    return obj;
  };

  const [localFilters, setLocalFilters] =
    useState<Record<string, string[]>>(getInitialFilters);

  // ✅ Only update local state (NO router call here)
  function handleCheckboxChange(
    sectionId: string,
    optionValue: string,
    checked: boolean
  ) {
    setLocalFilters((prev) => {
      const existing = prev[sectionId] || [];

      const updated = checked
        ? [...new Set([...existing, optionValue])]
        : existing.filter((item) => item !== optionValue);

      return {
        ...prev,
        [sectionId]: updated,
      };
    });
  }

  // ✅ Apply filter updates URL only once
  function handleApplyFilter() {
    const params = new URLSearchParams();

    Object.entries(localFilters).forEach(([key, values]) => {
      if (values.length > 0) {
        params.set(key, values.join(","));
      }
    });

    router.replace(`?${params.toString()}`, { scroll: false });

    closeSidebar();
  }

  // ✅ Clear everything
  function handleClearFilter() {
    setLocalFilters({});
    const params = new URLSearchParams();
    router.replace(`?${params.toString()}`, { scroll: false });
  }

  return (
    <div>
      <div className="flex w-full flex-row items-center justify-center gap-5 py-2 align-middle">
        <button className="btn-outline" onClick={handleApplyFilter}>
          Apply Filter
        </button>
        <button className="btn-link" onClick={handleClearFilter}>
          Clear All
        </button>
      </div>
      <div className="flex max-h-lvh w-full flex-col overflow-x-hidden overflow-y-auto">
        <div className="flex h-full w-full pt-5 flex-col pb-40">
          {filterData.map((section) => (
            <Disclosure
              key={section.id}
              as="div"
              className="border-b border-gray-300 py-2 pt-3"
            >
              <h3 className="-my-1 flow-root">
                <DisclosureButton className="group flex w-full items-center justify-between bg-white py-3 text-sm text-gray-400 hover:text-gray-500">
                  <span className="text-base font-medium tracking-wider text-gray-900 uppercase">
                    {section.name}
                  </span>
                  <span className="ml-6 flex items-center">
                    <i
                      aria-hidden="true"
                      className="icon-[majesticons--chevron-down-line] size-6 group-data-open:hidden"
                    ></i>
                    <i
                      aria-hidden="true"
                      className="icon-[majesticons--chevron-up-line] size-6 group-not-data-open:hidden"
                    ></i>
                  </span>
                </DisclosureButton>
              </h3>
              <DisclosurePanel className="py-2">
                <div className="space-y-2.5">
                  {section.options.map((option, optionIdx) => (
                    <div key={option.value} className="flex gap-2">
                      <div className="flex h-4 shrink-0 items-center">
                        <div className="group grid size-4 grid-cols-1">
                          {/* <input
                            value={option.value}
                            checked={option.checked}
                            id={`filter-${section.id}-${optionIdx}`}
                         
                            name={`${section.id}[]`}
                            type="checkbox"
                            className="relative top-[2px] col-start-1 row-start-1 appearance-none border-2 border-gray-950 checked:bg-gray-950"
                            onChange={(e) =>
                              handleCheckboxChange(
                                section.id,
                                option.value,
                                e.target.checked,
                              )
                            }
                          /> */}
                        <input
                            value={option.value}
                            checked={
                              localFilters[section.id]?.includes(
                                option.value
                              ) || false
                            }
                            id={`filter-${section.id}-${optionIdx}`}
                            name={`${section.id}[]`}
                            type="checkbox"
                            className="relative top-[2px] col-start-1 row-start-1 appearance-none border-2 border-gray-950 checked:bg-gray-950"
                            onChange={(e) =>
                              handleCheckboxChange(
                                section.id,
                                option.value,
                                e.target.checked
                              )
                            }
                          />
                          <span className="pointer-events-none col-start-1 row-start-1 size-4 self-center justify-self-center stroke-white group-has-[:disabled]:stroke-gray-950/25">
                            <i className="icon-[iconamoon--check-bold] text-white opacity-0 group-has-[:checked]:opacity-100"></i>
                            <i className="icon-[iconamoon--check-bold] text-white opacity-0 group-has-[:indeterminate]:opacity-100"></i>
                          </span>
                        </div>
                      </div>
                      <label
                        htmlFor={`filter-${section.id}-${optionIdx}`}
                        className="flex w-full text-sm capitalize"
                      >
                        {option.label}
                      </label>
                    </div>
                  ))}
                </div>
              </DisclosurePanel>
            </Disclosure>
          ))}
        </div>
      </div>
    </div>
  );
}
