"use client";

import { useState, useMemo } from "react";
import { SearchInput } from "@/components/ui/SearchInput";
import { SegmentedToggle } from "@/components/ui/SegmentedToggle";
import { LeadTable } from "@/components/admin/leads/LeadTable";
import { LeadsKanbanBoard } from "@/components/admin/leads/LeadsKanbanBoard";
import type { LeadWithTags, LeadFieldOptions } from "@/lib/admin-queries";

export function LeadsViewToggle({
  leads,
  options,
}: {
  leads: LeadWithTags[];
  options: LeadFieldOptions;
}) {
  const [view, setView] = useState<"list" | "kanban">("list");
  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="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <SearchInput
          placeholder="Cerca lead..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          containerClassName="w-full md:w-80"
        />
        <SegmentedToggle
          options={[
            { value: "list", label: "Lista" },
            { value: "kanban", label: "Kanban" },
          ]}
          value={view}
          onChange={setView}
          className="self-start md:self-auto flex-shrink-0"
        />
      </div>

      {view === "list" ? (
        <LeadTable leads={filtered} total={leads.length} options={options} />
      ) : (
        <LeadsKanbanBoard leads={filtered} />
      )}
    </div>
  );
}
