"use client";

// Client-side search widget backing /trahs/[trahId]/search (T-508,
// REQ-SRCH-001). Submit-based (not live/debounced) — simpler to reason
// about and test, and the ticket explicitly allows either. Calls the
// GET /api/trahs/[trahId]/search?q= route (never Prisma directly — this is
// a Client Component).
import { useState, type FormEvent } from "react";
import Link from "next/link";

type PersonSummary = {
  id: string;
  displayName: string;
};

export default function SearchPanel({ trahId }: { trahId: string }) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<PersonSummary[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  async function runSearch(q: string) {
    const trimmed = q.trim();
    if (trimmed.length === 0) {
      setError("Enter a name to search.");
      setResults(null);
      return;
    }

    setError(null);
    setBusy(true);
    try {
      const res = await fetch(`/api/trahs/${trahId}/search?q=${encodeURIComponent(trimmed)}`);
      if (res.ok) {
        const data = (await res.json()) as { results: PersonSummary[] };
        setResults(data.results);
        return;
      }

      if (res.status === 401) {
        setError("You need to be signed in to search.");
      } else if (res.status === 403) {
        setError("You don't have permission to search this Trah.");
      } else {
        setError("Search failed. Please try again.");
      }
      setResults(null);
    } catch {
      setError("Something went wrong. Please try again.");
      setResults(null);
    } finally {
      setBusy(false);
    }
  }

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    await runSearch(query);
  }

  return (
    <div>
      <form onSubmit={handleSubmit} style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}>
        <label htmlFor="search-query" style={{ display: "none" }}>
          Search by name
        </label>
        <input
          id="search-query"
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search by name…"
          style={{ flex: 1, padding: "0.4rem 0.6rem" }}
        />
        <button type="submit" disabled={busy}>
          {busy ? "Searching…" : "Search"}
        </button>
      </form>

      {error && (
        <p role="alert" style={{ color: "crimson" }}>
          {error}
        </p>
      )}

      {results !== null && (
        <ul style={{ listStyle: "none", margin: 0, padding: 0 }}>
          {results.length === 0 ? (
            <p style={{ color: "#999" }}>No matching persons found.</p>
          ) : (
            results.map((person) => (
              <li key={person.id} style={{ padding: "0.35rem 0" }}>
                <Link href={`/trahs/${trahId}/persons/${person.id}/profile`}>
                  {person.displayName}
                </Link>
              </li>
            ))
          )}
        </ul>
      )}
    </div>
  );
}
