import { expect, test } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import { renderApp } from "../test/render";
import { FilteredRecordList } from "./filtered-record-list";
import { labelText } from "../lib/labels";

type Rec = { id: string; labels: { lang: string; label: string }[] };
const recs: Rec[] = [
  { id: "a", labels: [{ lang: "en", label: "Alpha" }] },
  { id: "b", labels: [{ lang: "en", label: "Beta" }] },
];
const row = (r: Rec) => <li>{labelText(r.labels, "en")}</li>;

test("filtering narrows the rendered rows", async () => {
  renderApp(
    <FilteredRecordList records={recs} lang="en" isLoading={false} isError={false}
      loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
  );
  expect(screen.getByText("Alpha")).toBeInTheDocument();
  expect(screen.getByText("Beta")).toBeInTheDocument();
  await userEvent.type(screen.getByLabelText(/filter/i), "alph");
  expect(screen.getByText("Alpha")).toBeInTheDocument();
  expect(screen.queryByText("Beta")).toBeNull();
});

test("empty records show the empty text", () => {
  renderApp(
    <FilteredRecordList records={[]} lang="en" isLoading={false} isError={false}
      loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
  );
  expect(screen.getByText("EmptyMsg")).toBeInTheDocument();
});

test("non-empty records with a non-matching filter show no-matches", async () => {
  renderApp(
    <FilteredRecordList records={recs} lang="en" isLoading={false} isError={false}
      loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
  );
  await userEvent.type(screen.getByLabelText(/filter/i), "zzz");
  expect(screen.getByText(/no matches/i)).toBeInTheDocument();
});

test("an error shows the load-error text", () => {
  renderApp(
    <FilteredRecordList records={undefined} lang="en" isLoading={false} isError={true}
      loadErrorText="LoadErr" emptyText="EmptyMsg" renderRow={row} />,
  );
  expect(screen.getByText("LoadErr")).toBeInTheDocument();
});
