import React from "react"
import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import TextField from "../../../components/text-field"
import Button from "../../../components/button"
import useForm, { Form } from "../../../hooks/use-form"

import { rest } from "msw"
import { setupServer } from "msw/node"

const server = setupServer()

beforeAll(() => server.listen())
// reset any request handlers that are declared as a part of our tests
// (i.e. for testing one-time error scenarios)
afterEach(() => server.resetHandlers())
// clean up once the tests are done
afterAll(() => server.close())

const ExampleForm = (props) => {
  const form = useForm({ initialData: { name: "", email: "" } })

  return (
    <Form form={form} {...props}>
      <TextField label="Name" name="name" />
      <TextField label="Email" name="email" />
      <Button>Submit</Button>
    </Form>
  )
}

jest.useFakeTimers()

describe("Form validations", () => {
  test("should validate async", async () => {
    server.use(
      rest.post("/validations", (req, res, ctx) => {
        return res(ctx.json([{ field: "name", message: "name is invalid" }]))
      })
    )

    render(<ExampleForm validation="demo_validation" />)

    userEvent.type(screen.getByLabelText("Name"), "Brendan")

    userEvent.type(screen.getByLabelText("Email"), "brendan@convertkit.com")

    jest.advanceTimersByTime(8000)

    const error = await screen.findByText("name is invalid")
    expect(error).toBeInTheDocument()
  })
})
