// PURPOSE: Corpus search (spec §5) — the input + results panel, lifted out of
//          the app so every consumer (embedded + standalone) renders search the
//          same way instead of hand-rolling hit rendering. Owns query state,
//          paginated results, loading/error/clear; shows the caller's `browse`
//          content when there is no active search. Pure: the actual search runs
//          through an injected `onSearch` callback.
// ===========================================================================
import { useState, type FC, type FormEvent, type ReactNode } from "react";
import { Loader2, Search, X } from "lucide-react";
import type { ObjectSummary, SearchHit, SearchPage } from "./types";
import { ObjectList } from "./components-object";

function hitToSummary(h: SearchHit): ObjectSummary {
  return {
    object_id: h.object_id,
    kind: h.kind,
    title: h.title,
    status: "active",
    updated_at: h.updated_at ?? "",
    effective_at: h.effective_at ?? null,
    sensitivity: h.sensitivity,
  };
}

export interface KnowledgeSearchProps {
  /** Run a search and return a page; `cursor` drives "Load more". */
  onSearch: (query: string, cursor?: string) => Promise<SearchPage>;
  onOpen?: (objectId: string) => void;
  placeholder?: string;
  /** Shown below the input while there is no active search (the browse list). */
  browse?: ReactNode;
  className?: string;
}

export const KnowledgeSearch: FC<KnowledgeSearchProps> = ({
  onSearch,
  onOpen,
  placeholder,
  browse,
  className,
}) => {
  const [query, setQuery] = useState("");
  const [hits, setHits] = useState<SearchHit[] | null>(null);
  const [cursor, setCursor] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function clear() {
    setHits(null);
    setCursor(null);
    setQuery("");
    setError(null);
  }

  async function run(e?: FormEvent) {
    e?.preventDefault();
    const q = query.trim();
    if (!q) {
      clear();
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const page = await onSearch(q);
      setHits(page.hits);
      setCursor(page.next_cursor ?? null);
    } catch {
      setError("Search failed. Try again.");
    } finally {
      setLoading(false);
    }
  }

  async function loadMore() {
    if (!cursor || loadingMore) return;
    setLoadingMore(true);
    try {
      const page = await onSearch(query.trim(), cursor);
      setHits((prev) => [...(prev ?? []), ...page.hits]);
      setCursor(page.next_cursor ?? null);
    } catch {
      setError("Couldn't load more results. Try again.");
    } finally {
      setLoadingMore(false);
    }
  }

  return (
    <div className={className}>
      <form onSubmit={run} className="mb-4 flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
          <input
            data-action="knowledge-search"
            className="w-full rounded-lg border border-border bg-background py-2 pl-9 pr-9 text-sm outline-none focus:border-primary/50 focus:ring-2 focus:ring-primary/30"
            placeholder={placeholder ?? "Search…"}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          {query && (
            <button
              type="button"
              onClick={clear}
              aria-label="Clear search"
              className="absolute right-2 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground transition-colors hover:text-foreground"
            >
              <X className="size-4" />
            </button>
          )}
        </div>
      </form>

      {loading ? (
        <p className="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">
          <Loader2 className="size-4 animate-spin" /> Searching…
        </p>
      ) : error ? (
        <p className="rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive">
          {error}
        </p>
      ) : hits ? (
        <div>
          <div className="mb-2 flex items-center justify-between text-xs text-muted-foreground">
            <span>
              {hits.length} result{hits.length === 1 ? "" : "s"}
            </span>
            <button type="button" className="transition-colors hover:text-foreground" onClick={clear}>
              Clear
            </button>
          </div>
          <ObjectList
            objects={hits.map(hitToSummary)}
            onOpen={(o) => onOpen?.(o.object_id)}
            onLoadMore={loadMore}
            hasMore={!!cursor}
            loadingMore={loadingMore}
            emptyState={
              <div className="rounded-xl border border-dashed border-border py-12 text-center text-sm text-muted-foreground">
                No matches.
              </div>
            }
          />
        </div>
      ) : (
        (browse ?? null)
      )}
    </div>
  );
};
