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

import { renderApp } from "../test/render";
import { LabelledRecordCreateForm } from "./labelled-record-create-form";

test("submitting with empty labels shows the required error and does not call onCreate", async () => {
  const onCreate = vi.fn();
  renderApp(
    <LabelledRecordCreateForm heading="New" submitLabel="Create" pending={false} error={null} onCreate={onCreate} />,
  );
  await userEvent.click(screen.getByRole("button", { name: /create/i }));
  expect(screen.getByRole("alert")).toBeInTheDocument();
  expect(onCreate).not.toHaveBeenCalled();
});

test("a valid submit calls onCreate and the reset clears the inputs", async () => {
  const onCreate = vi.fn((_labels: unknown, _uri: unknown, reset: () => void) => reset());
  renderApp(
    <LabelledRecordCreateForm heading="New" submitLabel="Create" pending={false} error={null} onCreate={onCreate} />,
  );
  const labelInput = screen.getByLabelText(/^label$/i) as HTMLInputElement;
  await userEvent.type(labelInput, "Bronze");
  await userEvent.click(screen.getByRole("button", { name: /create/i }));
  expect(onCreate).toHaveBeenCalled();
  expect((screen.getByLabelText(/^label$/i) as HTMLInputElement).value).toBe("");
});
