// @design-system: domain/facets/PriceRangeFacet
'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import { Slider } from '@/components/ui/primitives/Slider';
import { formatAgorotWhole } from '@/lib/money';
import { useT } from '@/lib/i18n/react';
import { FacetSection } from './FacetSection';

export interface PriceRangeFacetProps {
  label: string;
  /** Domain floor (shekels) — slider min and histogram axis bottom. */
  floor: number;
  ceiling: number;
  value: [number, number];
  onChange: (range: [number, number]) => void;
  /** Defaults to '₪' */
  currency?: string;
  /** Slider step in whole shekels. Defaults to 10. */
  step?: number;
  /** Deal counts per price bucket, forwarded to the slider bars. */
  histogram?: number[];
  /** Builds the per-bar tooltip text; forwarded to the slider. */
  formatBarTooltip?: (count: number, lo: number, hi: number) => string;
  /** Debounce interval for parent onChange. Defaults to 300ms. */
  debounceMs?: number;
}

export function PriceRangeFacet({
  label,
  floor,
  ceiling,
  value,
  onChange,
  currency: _currency = '₪',
  step = 10,
  histogram,
  formatBarTooltip,
  debounceMs = 300,
}: PriceRangeFacetProps) {
  const t = useT('common');
  const [localRange, setLocalRange] = useState(value);
  const [prevValue, setPrevValue] = useState(value);
  const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);

  // Sync local state when the controlled value changes from outside.
  if (prevValue !== value) {
    setPrevValue(value);
    setLocalRange(value);
  }

  const handleChange = useCallback(
    (next: [number, number]) => {
      setLocalRange(next);
      if (timerRef.current) clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => {
        onChange(next);
      }, debounceMs);
    },
    [onChange, debounceMs],
  );

  useEffect(() => {
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, []);

  const formatPrice = useCallback((v: number) => formatAgorotWhole(v * 100), []);

  const formatMaxLabel = useCallback(
    (v: number) => {
      const formatted = formatPrice(v);
      return v >= ceiling ? `${formatted}${t('price_overflow_suffix')}` : formatted;
    },
    [ceiling, formatPrice, t],
  );

  return (
    <FacetSection label={label}>
      <Slider
        min={floor}
        max={ceiling}
        step={step}
        value={localRange}
        onChange={handleChange}
        histogram={histogram}
        formatBarTooltip={formatBarTooltip}
        showRangeInput
        formatLabel={formatPrice}
        formatMaxLabel={formatMaxLabel}
        aria-label={label}
      />
    </FacetSection>
  );
}
