"use client";

import { ChevronDown, X } from "lucide-react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import Link from "next/link";

const FilterSection = ({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) => {
  const [open, setOpen] = useState(true);

  return (
    <div className="ltfilterbx">
      <div className="ltfilterheading">
        <a href="javascript:void(0);">{title}</a>

        <button
          className={`collapsebtn ${open ? "active" : ""}`}
          type="button"
          onClick={() => setOpen(!open)}
        >
          <ChevronDown
            size={18}
            className={`transition-transform duration-300 ${
              open ? "rotate-180" : "rotate-0"
            }`}
          />
        </button>
      </div>

      {open && (
        <div className="ltfilterbody active">
          <div className="ltfilterbodyinner">{children}</div>
        </div>
      )}
    </div>
  );
};

type Props = {
  onClose: () => void;
  filters: any;
  selectedFilters: any;
  onToggle: (key: string, value: string) => void;
  onPriceChange: (min: number, max: number) => void;
};

export default function ProductFilter({
  onClose,
  filters,
  selectedFilters,
  onToggle,
  onPriceChange,
}: Props) {
  const uniqueSizesMap = new Map();

  (filters?.sizes || []).forEach((size: any) => {
    const key = size.name.trim().toUpperCase();

    // keep first OR highest priority (lowest sortOrder wins)
    if (!uniqueSizesMap.has(key)) {
      uniqueSizesMap.set(key, size);
    } else {
      const existing = uniqueSizesMap.get(key);

      if ((size.sortOrder ?? 999) < (existing.sortOrder ?? 999)) {
        uniqueSizesMap.set(key, size);
      }
    }
  });

  const uniqueSizes = Array.from(uniqueSizesMap.values());

  const sortedSizes = uniqueSizes?.sort(
    (a: any, b: any) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0),
  );

  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const updateQueryParams = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams.toString());

    // CATEGORY => single select
    if (key === "category") {
      if (params.get("category") === value) {
        params.delete("category");
        params.delete("subcategory");
      } else {
        params.set("category", value);
        params.delete("subcategory");
      }

      router.replace(`${pathname}?${params.toString()}`);

      return;
    }

    // SUBCATEGORY => multi select
    const existingValues = params.get(key)?.split(",") || [];

    let updatedValues: string[];

    if (existingValues.includes(value)) {
      updatedValues = existingValues.filter((v) => v !== value);
    } else {
      updatedValues = [...existingValues, value];
    }

    if (updatedValues.length > 0) {
      params.set(key, updatedValues.join(","));
    } else {
      params.delete(key);
    }

    router.replace(`${pathname}?${params.toString()}`);
  };

  return (
    <div className="leftfilterouter">
      {/* Header */}
      <div style={{ display: "flex", alignItems: "center" }}>
        <div className="ltfiltertp">Filters</div>

        <button className="filterclose" onClick={onClose}>
          ✕
        </button>
      </div>

      <div className="mflexfill">
        <FilterSection title="Categories">
          {filters?.categories?.map((cat: any) => {
            const subs = filters?.subcategories?.filter(
              (sub: any) => sub.parent._id === cat._id,
            );
            const isChecked = selectedFilters.category === cat.slug;

            return (
              <div key={cat._id} className="filtercheckbx">
                <div className="form-check w-full">
                  <Link href={`/products?category=${cat.slug}`}>
                    <label
                      className="form-check-label"
                      style={{ color: isChecked ? "#DDA16B" : undefined }}
                    >
                      {cat.name}
                    </label>
                  </Link>
                </div>

                {/* Subcategories — only show when parent is selected */}
                {isChecked && subs?.length > 0 && (
                  <div className="pl-4">
                    {subs.map((sub: any) => {
                      const subChecked = (
                        selectedFilters.subcategory ?? []
                      ).includes(sub.slug);
                      return (
                        <div key={sub._id} className="form-check">
                          <input
                            type="checkbox"
                            checked={subChecked}
                            className="form-check-input"
                            onChange={() =>
                              updateQueryParams("subcategory", sub.slug)
                            }
                          />

                          <label
                            className="form-check-label"
                            onClick={() =>
                              updateQueryParams("subcategory", sub.slug)
                            }
                            style={{
                              color: subChecked ? "#DDA16B" : undefined,
                            }}
                          >
                            {sub.name}
                          </label>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </FilterSection>

        {/*  SIZES  */}
        <FilterSection title="Sizes">
          <div className="filtercheckbx flex flex-wrap">
            {sortedSizes?.map((size: any, index: number) => {
              const checked = selectedFilters.size.includes(size._id);

              return (
                // <div key={size._id} className='filtercheckbx flex flex-wrap'>
                <div key={size._id} className="form-check w-1/2">
                  <input
                    type="checkbox"
                    id={"check" + index}
                    checked={checked}
                    className="form-check-input"
                    onChange={() => onToggle("size", size._id)}
                  />
                  <label htmlFor={"check" + index} className="form-check-label">
                    {size.name?.toUpperCase()}
                  </label>
                </div>
                // </div>
              );
            })}
          </div>
        </FilterSection>

        {/* RATINGS */}
        <FilterSection title="Ratings">
          <div className="filtercheckbx">
            {filters?.reviewFilters?.map((rating: any, index: number) => {
              const checked = selectedFilters.ratings.includes(rating.value);

              return (
                <div key={rating.value} className="form-check w-full">
                  <input
                    type="checkbox"
                    checked={checked}
                    id={"rating" + index}
                    className="form-check-input"
                    onChange={() => onToggle("ratings", rating.value)}
                  />
                  <label
                    htmlFor={"rating" + index}
                    className="form-check-label"
                  >
                    {rating.label}
                  </label>
                </div>
              );
            })}
          </div>
        </FilterSection>

        {/* PRICE SLIDER */}
        <FilterSection title="Price">
          <style>{`
          .slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            position: absolute;
            width: 100%;
            height: 4px;
            background: transparent;
            outline: none;
            cursor: pointer;
          }
          .slider-thumb::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: rgba(221, 161, 107, 1);
            border: 3px solid rgba(221, 161, 107, 1);
            cursor: pointer;
            box-shadow: 0 2px 6px rgba(0,0,0,.15);
          }
          .slider-thumb::-moz-range-thumb {
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: rgba(221, 161, 107, 1);
            border: 3px solid rgba(221, 161, 107, 1);
            cursor: pointer;
            box-shadow: 0 2px 6px rgba(0,0,0,.15);
          }
          `}</style>
          <div className="price-range">
            <div
              className="range-wrap"
              style={{ position: "relative", height: "30px" }}
            >
              {/* Min thumb */}
              <input
                type="range"
                min={filters?.minPrice ?? 0}
                max={filters?.maxPrice ?? 10000}
                value={selectedFilters.price.min}
                onChange={(e) => {
                  const val = Number(e.target.value);
                  if (val < selectedFilters.price.max) {
                    onPriceChange(val, selectedFilters.price.max);
                  }
                }}
                style={{
                  position: "absolute",
                  width: "100%",
                  pointerEvents: "none", // All for click based change
                  appearance: "none",
                  background: "transparent",
                  zIndex:
                    selectedFilters.price.min > (filters?.maxPrice ?? 10000) / 2
                      ? 5
                      : 3,
                }}
                className="slider-thumb"
              />

              {/* Max thumb */}
              <input
                type="range"
                min={filters?.minPrice ?? 0}
                max={filters?.maxPrice ?? 10000}
                value={selectedFilters.price.max}
                onChange={(e) => {
                  const val = Number(e.target.value);
                  if (val > selectedFilters.price.min) {
                    onPriceChange(selectedFilters.price.min, val);
                  }
                }}
                style={{
                  position: "absolute",
                  width: "100%",
                  pointerEvents: "none",
                  appearance: "none",
                  background: "transparent",
                  zIndex:
                    selectedFilters.price.max < (filters?.maxPrice ?? 10000) / 2
                      ? 5
                      : 4,
                }}
                className="slider-thumb"
              />

              {/* Track */}
              <div
                className="slider-track"
                style={{
                  position: "absolute",
                  top: "50%",
                  transform: "translateY(-50%)",
                  height: "4px",
                  width: "100%",
                  borderRadius: "999px",
                  background: "#DFDFDF",
                }}
              >
                {/* Colored range between min and max */}
                <div
                  style={{
                    position: "absolute",
                    height: "100%",
                    borderRadius: "999px",
                    background: `rgba(${221}, ${161}, ${107}, 1)`,
                    left: `${((selectedFilters.price.min - (filters?.minPrice ?? 0)) / ((filters?.maxPrice ?? 10000) - (filters?.minPrice ?? 0))) * 100}%`,
                    right: `${100 - ((selectedFilters.price.max - (filters?.minPrice ?? 0)) / ((filters?.maxPrice ?? 10000) - (filters?.minPrice ?? 0))) * 100}%`,
                  }}
                />
              </div>
            </div>

            <div className="range-values mt-2 flex justify-between">
              <span>₹{selectedFilters.price.min.toLocaleString("en-IN")}</span>
              <span>₹{selectedFilters.price.max.toLocaleString("en-IN")}</span>
            </div>
          </div>
        </FilterSection>
      </div>
    </div>
  );
}
