import { expect, test } from "vitest";
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useForm } from "react-hook-form";
import { renderApp } from "../test/render";
import { FieldInput } from "./field-input";
import { fieldDefinitions } from "../test/fixtures";

type FormValues = { fields: Record<string, unknown> };

function Harness({ defKey }: { defKey: string }) {
  const def = fieldDefinitions.find((d) => d.key === defKey)!;
  const form = useForm({ defaultValues: { fields: {} as Record<string, unknown> } });

  return <FieldInput definition={def} form={form} />;
}

function FormHarness({
  defKey,
  onSubmit,
}: {
  defKey: string;
  onSubmit: (values: FormValues) => void;
}) {
  const def = fieldDefinitions.find((d) => d.key === defKey)!;
  const form = useForm<FormValues>({ defaultValues: { fields: {} as Record<string, unknown> } });

  return (
    <form onSubmit={form.handleSubmit(onSubmit)}>
      <FieldInput definition={def} form={form} />
      <button type="submit">Submit</button>
    </form>
  );
}

test("text field renders a text input labelled in the active locale", async () => {
  renderApp(<Harness defKey="inscription" />);
  expect(await screen.findByLabelText("Inscription")).toBeInTheDocument();
});

test("boolean field renders a checkbox", async () => {
  renderApp(<Harness defKey="is_fragment" />);
  expect(await screen.findByRole("checkbox", { name: /is fragment/i })).toBeInTheDocument();
});

test("localized_text renders a single input for the default language", async () => {
  renderApp(<Harness defKey="title_ml" />);
  expect(await screen.findByLabelText(/^title/i)).toBeInTheDocument();
});

test("term field filters and selects from the vocabulary combobox", async () => {
  const user = userEvent.setup();
  const submitted: FormValues[] = [];

  renderApp(<FormHarness defKey="material" onSubmit={(v) => submitted.push(v)} />);

  const input = await screen.findByPlaceholderText("— select —");

  await user.click(input);
  await user.type(input, "bro");

  const body = within(document.body);

  await user.click(await body.findByText("Bronze"));
  await user.click(screen.getByRole("button", { name: "Submit" }));

  expect(submitted[0]?.fields.material).toBe("t-bronze");
});

test("authority field filters and selects from the authority combobox", async () => {
  const user = userEvent.setup();
  const submitted: FormValues[] = [];

  renderApp(<FormHarness defKey="maker" onSubmit={(v) => submitted.push(v)} />);

  const input = await screen.findByPlaceholderText("— select —");

  await user.click(input);
  await user.type(input, "ada");

  const body = within(document.body);

  await user.click(await body.findByText("Ada Lovelace"));
  await user.click(screen.getByRole("button", { name: "Submit" }));

  expect(submitted[0]?.fields.maker).toBe("a-ada");
});
