"use client";

import { useState, useMemo } from "react";
import { Input } from "@/components/ui/input";
import { Search } from "lucide-react";
import { LeadTable } from "@/components/admin/leads/LeadTable";
import type { LeadWithTags, LeadFieldOptions } from "@/lib/admin-queries";

export function LeadsSearch({
  leads,
  options,
}: {
  leads: LeadWithTags[];
  options: LeadFieldOptions;
}) {
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return leads;
    return leads.filter((l) => {
      if (l.name.toLowerCase().includes(q)) return true;
      if (l.email?.toLowerCase().includes(q)) return true;
      if (l.company?.toLowerCase().includes(q)) return true;
      if (l.status.toLowerCase().includes(q)) return true;
      if (l.tags.some((t) => t.toLowerCase().includes(q))) return true;
      return false;
    });
  }, [leads, 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 lead..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          className="pl-9 h-9"
        />
      </div>
      <LeadTable leads={filtered} options={options} />
    </div>
  );
}
