"use client";

import { useState, useMemo } from "react";
import { Input } from "@/components/ui/input";
import { Search } from "lucide-react";
import { ServiceTable } from "@/components/admin/catalog/ServiceTable";
import type { ServiceWithTags, CatalogFieldOptions } from "@/lib/admin-queries";

export function CatalogSearch({
  services,
  options,
}: {
  services: ServiceWithTags[];
  options: CatalogFieldOptions;
}) {
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return services;
    return services.filter((s) => {
      if (s.name.toLowerCase().includes(q)) return true;
      if (s.category?.toLowerCase().includes(q)) return true;
      if (s.fase?.toLowerCase().includes(q)) return true;
      if (s.tags.some((t) => t.toLowerCase().includes(q))) return true;
      if (s.pacchetto.some((p) => p.toLowerCase().includes(q))) return true;
      return false;
    });
  }, [services, query]);

  return (
    <div className="space-y-4">
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[#71717a]" />
        <Input
          type="text"
          placeholder="Cerca per nome, categoria, fase, tag o pacchetto..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          className="pl-9 h-9"
        />
      </div>
      <ServiceTable services={filtered} options={options} />
    </div>
  );
}
