"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";

import { Slider } from "@/components/ui/slider";
import { buildItemSearchUrl, type ItemSearchParams } from "@/lib/item-search-params";

interface PriceFacetProps {
  bounds: { min: number; max: number };
  params: ItemSearchParams;
}

function formatDollars(cents: number): string {
  return `$${Math.round(cents / 100)}`;
}

export function PriceFacet({ bounds, params }: PriceFacetProps) {
  const router = useRouter();
  const [value, setValue] = useState<[number, number]>([
    params.minPrice ?? bounds.min,
    params.maxPrice ?? bounds.max,
  ]);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

  // Sync local slider state when URL params change (legitimate external-to-local sync)
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- syncing URL params to local slider state
    setValue([params.minPrice ?? bounds.min, params.maxPrice ?? bounds.max]);
    return () => {
      if (timer.current) clearTimeout(timer.current);
    };
  }, [params.minPrice, params.maxPrice, bounds.min, bounds.max]);

  function onValueChange(next: number[]) {
    const tuple: [number, number] = [next[0] ?? bounds.min, next[1] ?? bounds.max];
    setValue(tuple);

    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      router.push(
        buildItemSearchUrl(params, {
          minPrice: tuple[0] === bounds.min ? null : tuple[0],
          maxPrice: tuple[1] === bounds.max ? null : tuple[1],
        }),
      );
    }, 300);
  }

  if (bounds.min === bounds.max) return null;

  return (
    <div className="space-y-3">
      <h3 className="text-sm font-semibold text-slate-900">Price</h3>
      <div className="flex items-center justify-between text-xs text-slate-600">
        <span>{formatDollars(value[0])}</span>
        <span>{formatDollars(value[1])}</span>
      </div>
      <Slider
        min={bounds.min}
        max={bounds.max}
        step={500}
        value={value}
        onValueChange={onValueChange}
      />
    </div>
  );
}
