"use client";

import { useState } from "react";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import type { FacetCount } from "./types";

interface CheckboxFacetProps {
  title: string;
  facets: FacetCount[];
  selected: string[];
  onChange: (next: string[]) => void;
  searchThreshold?: number;
}

export function CheckboxFacet({
  title,
  facets,
  selected,
  onChange,
  searchThreshold = 15,
}: CheckboxFacetProps) {
  const [query, setQuery] = useState("");
  const showSearch = facets.length >= searchThreshold;
  const visible = showSearch
    ? facets.filter((f) => (f.label ?? f.value).toLowerCase().includes(query.toLowerCase()))
    : facets;

  function toggle(value: string) {
    onChange(selected.includes(value) ? selected.filter((v) => v !== value) : [...selected, value]);
  }

  return (
    <div className="space-y-2">
      <h3 className="text-sm font-semibold text-slate-900">{title}</h3>
      {showSearch && (
        <Input
          placeholder={`Search ${title.toLowerCase()}...`}
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          className="h-8 text-xs"
        />
      )}
      <ul className="max-h-64 space-y-1 overflow-y-auto">
        {visible.map((f) => (
          <li key={f.value} className="flex items-center gap-2 text-sm">
            <Checkbox
              id={`${title}-${f.value}`}
              checked={selected.includes(f.value)}
              onCheckedChange={() => toggle(f.value)}
            />
            <label htmlFor={`${title}-${f.value}`} className="flex flex-1 items-center justify-between">
              <span>{f.label ?? f.value}</span>
              <span className="text-xs text-slate-500">{f.count}</span>
            </label>
          </li>
        ))}
      </ul>
    </div>
  );
}
