"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { formatPrice } from "../../lib/format";

// Two overlapping native <input type="range"> thumbs (a plain CSS trick —
// track transparent/pointer-events-none, only the thumb itself clickable
// via the ::-webkit-slider-thumb/::-moz-range-thumb pseudo-elements) —
// replaced the earlier two-number-input version (2026-08-01) for a more
// direct "drag to filter" feel. `onInput` updates the visual position on
// every drag frame; the URL/navigation only commits on `onChange` (fires
// once, on mouse-up/key-up), so dragging doesn't spam router.push.
export function PriceRangeFilter({
  catalogMin,
  catalogMax,
  layout = "bar",
}: {
  catalogMin: number;
  catalogMax: number;
  /** "bar" (default): horizontal row — used above the grid at <lg (see
   * ProductGrid.tsx's mobile/tablet filter bar). "sidebar": stacked to
   * fit the lg:+ left sidebar column instead. */
  layout?: "bar" | "sidebar";
}) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const paramMin = searchParams.get("minPrice");
  const paramMax = searchParams.get("maxPrice");
  const [minPrice, setMinPrice] = useState(paramMin ? Number(paramMin) : catalogMin);
  const [maxPrice, setMaxPrice] = useState(paramMax ? Number(paramMax) : catalogMax);

  const hasFilter = Boolean(paramMin || paramMax);
  const sidebar = layout === "sidebar";

  function commit(nextMin: number, nextMax: number) {
    const params = new URLSearchParams(searchParams.toString());
    if (nextMin > catalogMin) params.set("minPrice", String(nextMin));
    else params.delete("minPrice");
    if (nextMax < catalogMax) params.set("maxPrice", String(nextMax));
    else params.delete("maxPrice");
    const qs = params.toString();
    router.push(qs ? `/shop?${qs}` : "/shop");
  }

  function reset() {
    setMinPrice(catalogMin);
    setMaxPrice(catalogMax);
    const params = new URLSearchParams(searchParams.toString());
    params.delete("minPrice");
    params.delete("maxPrice");
    const qs = params.toString();
    router.push(qs ? `/shop?${qs}` : "/shop");
  }

  // Clamped against each other while dragging — a thumb can't be pushed
  // past its sibling, so the range never visually inverts.
  function onMinInput(value: number) {
    setMinPrice(Math.min(value, maxPrice));
  }
  function onMaxInput(value: number) {
    setMaxPrice(Math.max(value, minPrice));
  }

  const range = catalogMax - catalogMin || 1;
  const minPct = ((minPrice - catalogMin) / range) * 100;
  const maxPct = ((maxPrice - catalogMin) / range) * 100;

  const thumbClasses =
    "absolute w-full m-0 appearance-none bg-transparent pointer-events-none " +
    "[&::-webkit-slider-thumb]:pointer-events-auto [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-brand [&::-webkit-slider-thumb]:cursor-pointer [&::-webkit-slider-thumb]:shadow-sm " +
    "[&::-moz-range-thumb]:pointer-events-auto [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-brand [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:cursor-pointer " +
    "[&::-webkit-slider-runnable-track]:bg-transparent [&::-moz-range-track]:bg-transparent";

  return (
    <div className={sidebar ? "flex flex-col gap-3 items-stretch w-full" : "flex flex-col gap-2 w-full pb-6 sm:max-w-xs"}>
      {sidebar && <p className="font-bold text-body-sm text-text-primary">Preis</p>}
      <div className="flex items-center justify-between text-label text-text-muted">
        <span>{formatPrice(minPrice)}</span>
        <span>{formatPrice(maxPrice)}</span>
      </div>
      <div className="relative h-4 flex items-center">
        <div className="absolute inset-x-0 h-1 rounded-full bg-bg-muted" />
        <div className="absolute h-1 rounded-full bg-brand" style={{ left: `${minPct}%`, right: `${100 - maxPct}%` }} />
        <input
          type="range"
          aria-label="Mindestpreis"
          min={catalogMin}
          max={catalogMax}
          step="0.1"
          value={minPrice}
          onInput={(e) => onMinInput(Number(e.currentTarget.value))}
          onChange={() => commit(minPrice, maxPrice)}
          className={thumbClasses}
        />
        <input
          type="range"
          aria-label="Höchstpreis"
          min={catalogMin}
          max={catalogMax}
          step="0.1"
          value={maxPrice}
          onInput={(e) => onMaxInput(Number(e.currentTarget.value))}
          onChange={() => commit(minPrice, maxPrice)}
          className={thumbClasses}
        />
      </div>
      {hasFilter && (
        <button
          type="button"
          onClick={reset}
          className="self-start text-body-sm font-semibold text-text-muted underline hover:text-brand transition-colors"
        >
          Zurücksetzen
        </button>
      )}
    </div>
  );
}
