import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import React from "react";
import * as v from "valibot";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Form } from "./form";
afterEach(cleanup);
describe("Form Component", () => {
    it("should handle checkbox submission correctly (unchecked = false)", () => {
        const schema = v.object({
            check: v.boolean(),
        });
        const onSubmit = vi.fn();
        render(<Form schema={schema} onSubmit={onSubmit}>
                <input type="checkbox" name="check" data-testid="checkbox"/>
                <button type="submit">Submit</button>
            </Form>);
        // Submit without checking
        fireEvent.click(screen.getByText("Submit"));
        expect(onSubmit).toHaveBeenCalledTimes(1);
        expect(onSubmit).toHaveBeenCalledWith({ check: false });
    });
    it("should handle checkbox submission correctly (checked = true)", () => {
        const schema = v.object({
            check: v.boolean(),
        });
        const onSubmit = vi.fn();
        render(<Form schema={schema} onSubmit={onSubmit}>
                <input type="checkbox" name="check" data-testid="checkbox"/>
                <button type="submit">Submit</button>
            </Form>);
        // Check and submit
        fireEvent.click(screen.getByTestId("checkbox"));
        fireEvent.click(screen.getByText("Submit"));
        expect(onSubmit).toHaveBeenCalledTimes(1);
        expect(onSubmit).toHaveBeenCalledWith({ check: true });
    });
    it("should set isSubmitted on validation error and report validity", () => {
        const schema = v.object({
            requiredField: v.pipe(v.string(), v.minLength(1)),
        });
        const onSubmit = vi.fn();
        render(<Form schema={schema} onSubmit={onSubmit}>
                <input name="requiredField" data-testid="input"/>
                <button type="submit">Submit</button>
            </Form>);
        const input = screen.getByTestId("input");
        // Mock reportValidity on the instance
        input.reportValidity = vi.fn();
        fireEvent.click(screen.getByText("Submit"));
        expect(onSubmit).toHaveBeenCalledTimes(0);
        expect(input.reportValidity).toHaveBeenCalledTimes(1);
    });
});
