"use client";

import * as React from "react";
import { Slider } from "@/components/ui/slider";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { t } from "@/lib/i18n/de";
import type { FacetDef } from "@/lib/search/types";

type Props = {
  facet: FacetDef;
  /** Aktueller URL-Wert `lo..hi` (oder undefined). */
  value: string | undefined;
  /** Schreibt den neuen `lo..hi`-Wert (null entfernt den Filter). */
  onChange: (value: string | null) => void;
};

function parse(value: string | undefined, min: number, max: number): [number, number] {
  if (!value || !value.includes("..")) return [min, max];
  const parts = value.split("..");
  const loRaw = parts[0] ?? "";
  const hiRaw = parts[1] ?? "";
  const lo = loRaw === "" ? min : Number(loRaw);
  const hi = hiRaw === "" ? max : Number(hiRaw);
  return [Number.isFinite(lo) ? lo : min, Number.isFinite(hi) ? hi : max];
}

/**
 * Number-Facette als Doppel-Slider plus exakte Zahlenfelder. Schreibt `lo..hi`
 * in die URL; entspricht der Range den Facetten-Grenzen, wird der Filter entfernt.
 */
export function NumberRangeFacet({ facet, value, onChange }: Props) {
  const min = facet.min ?? 0;
  const max = facet.max ?? 100;
  const [lo, hi] = parse(value, min, max);

  const emit = React.useCallback(
    (nlo: number, nhi: number) => {
      if (nlo <= min && nhi >= max) {
        onChange(null);
        return;
      }
      const loPart = nlo <= min ? "" : String(nlo);
      const hiPart = nhi >= max ? "" : String(nhi);
      onChange(`${loPart}..${hiPart}`);
    },
    [onChange, min, max],
  );

  if (max <= min) return null; // keine sinnvolle Spanne

  const unit = facet.einheit ? ` (${facet.einheit})` : "";

  return (
    <fieldset className="flex flex-col gap-2">
      <Label className="text-sm font-medium text-anthrazit">
        {facet.name}
        {unit}
      </Label>
      <Slider
        min={min}
        max={max}
        value={[lo, hi]}
        onValueChange={(v) => emit(v[0] ?? min, v[1] ?? max)}
        aria-label={facet.name}
      />
      <div className="flex items-center gap-2 text-sm">
        <Input
          type="number"
          aria-label={`${facet.name} ${t("search.von")}`}
          value={lo}
          min={min}
          max={max}
          onChange={(e) => emit(Number(e.target.value), hi)}
          className="w-24"
        />
        <span className="text-anthrazit/50">–</span>
        <Input
          type="number"
          aria-label={`${facet.name} ${t("search.bis")}`}
          value={hi}
          min={min}
          max={max}
          onChange={(e) => emit(lo, Number(e.target.value))}
          className="w-24"
        />
      </div>
    </fieldset>
  );
}
