import {
  cleanup,
  render,
  screen,
} from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import assert from "node:assert";
import {
  afterEach,
  describe,
  mock,
  test,
} from "node:test";
import { Form } from "./index";

describe("Form", () => {
  afterEach(() => {
    cleanup();
  });

  test("renders rows with fields", () => {
    const rows = [
      {
        cols: [
          {
            field: {
              label: "Email",
              input: {
                type: "text",
                name: "email",
              },
            },
          },
        ],
      },
    ];

    render(<Form rows={rows} />);

    const input = document.querySelector("input[name='email']");
    assert.notStrictEqual(input, null);
    assert.notStrictEqual(screen.queryByText("Email"), null);
  });

  test("calls onSubmit when submit button is clicked", async () => {
    const user = userEvent.setup();
    const onSubmit = mock.fn((event) => event.preventDefault());

    render(
      <Form onSubmit={onSubmit}>
        <button type={"submit"}>Submit</button>
      </Form>
    );

    await user.click(screen.getByRole("button", { name: "Submit" }));
    assert.strictEqual(onSubmit.mock.calls.length, 1);
  });

  test("renders custom wrapper when isCustomWrapper=true", () => {
    render(
      <Form
        id={"custom-form"}
        isCustomWrapper={true}
      />
    );

    const form = screen.getByRole("form");
    assert.strictEqual(form.tagName, "DIV");
    assert.strictEqual(form.getAttribute("id"), "custom-form");
  });
});
