"use client";

import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { t } from "@/lib/i18n/de";
import type { FacetDef } from "@/lib/search/types";
import { useSearchUrl } from "./useSearchParams";
import { NumberRangeFacet } from "./facets/NumberRangeFacet";
import { EnumFacet } from "./facets/EnumFacet";
import { BooleanFacet } from "./facets/BooleanFacet";

/**
 * Dynamisches Filter-Panel. Rendert je `active`-Merkmal GENAU EIN UI-Element des
 * passenden Typs (number->Slider, enum->Multi-Select, boolean->Tri-State) und
 * schreibt Änderungen über `useSearchUrl` in die URL. Plus Status-Switch
 * (`bereit=1`). Reine Client-Komponente; die Facetten kommen serverseitig.
 */
export function FilterPanel({ facets }: { facets: FacetDef[] }) {
  const { params, setParam, resetFilters } = useSearchUrl();
  const nurEinsatzbereit = params.get("bereit") === "1";

  return (
    <aside className="flex flex-col gap-4" aria-label={t("search.filter")}>
      <div className="flex items-center justify-between">
        <h2 className="text-sm font-semibold text-anthrazit">
          {t("search.filter")}
        </h2>
        <Button variant="ghost" size="sm" type="button" onClick={resetFilters}>
          {t("search.filterZuruecksetzen")}
        </Button>
      </div>

      <div className="flex items-center justify-between">
        <Label htmlFor="nur-einsatzbereit" className="text-sm text-anthrazit">
          {t("search.nurEinsatzbereit")}
        </Label>
        <Switch
          id="nur-einsatzbereit"
          checked={nurEinsatzbereit}
          onCheckedChange={(on) => setParam("bereit", on ? "1" : null)}
        />
      </div>

      {facets.length === 0 ? (
        <p className="text-sm text-anthrazit/60">{t("search.keineFilter")}</p>
      ) : (
        <div className="flex flex-col gap-5">
          {facets.map((facet) => (
            <FacetField key={facet.merkmalId} facet={facet} />
          ))}
        </div>
      )}
    </aside>
  );
}

function FacetField({ facet }: { facet: FacetDef }) {
  const { params, setParam } = useSearchUrl();
  const key = `f.${facet.merkmalId}`;
  const value = params.get(key) ?? undefined;
  const onChange = (v: string | null) => setParam(key, v);

  switch (facet.typ) {
    case "number":
      return <NumberRangeFacet facet={facet} value={value} onChange={onChange} />;
    case "enum":
      return <EnumFacet facet={facet} value={value} onChange={onChange} />;
    case "boolean":
      return <BooleanFacet facet={facet} value={value} onChange={onChange} />;
    default:
      return null; // text wird nicht als Filter angeboten
  }
}
