import { composeStories } from "@storybook/react"
import { screen } from "@testing-library/react"
import { userEvent } from "@testing-library/user-event"
import React from "react"
import { expect, describe, test } from "vitest"
import { render } from "../../../tests/render"
import * as stories from "./Modal.stories"

const { Uncontrolled, Controlled, InitiallyOpen } = composeStories(stories)

describe("<Modal />", () => {
  test("Uncontrolled", async () => {
    render(<Uncontrolled />)

    await userEvent.click(screen.getByText("Open Modal"))

    expect(await screen.findByRole("dialog")).toBeInTheDocument()
    expect(screen.getByText("Title content")).toBeInTheDocument()
    expect(screen.getByText("Body content")).toBeInTheDocument()
  })

  test("closes on overlay click", async () => {
    render(<Uncontrolled />)

    await userEvent.click(screen.getByText("Open Modal"))

    expect(await screen.findByRole("dialog")).toBeInTheDocument()

    await userEvent.click(screen.getByTestId("Overlay"))

    expect(screen.queryByRole("dialog")).not.toBeInTheDocument()
  })

  test("closes on close icon click", async () => {
    render(<Uncontrolled />)

    await userEvent.click(screen.getByText("Open Modal"))

    expect(await screen.findByRole("dialog")).toBeInTheDocument()

    await userEvent.click(screen.getByLabelText("Close"))

    expect(screen.queryByRole("dialog")).not.toBeInTheDocument()
  })

  test("As a user I want modal to close on escape key press", async () => {
    render(<Uncontrolled />)

    await userEvent.click(screen.getByText("Open Modal"))

    expect(await screen.findByRole("dialog")).toBeInTheDocument()

    await userEvent.type(screen.getByRole("dialog"), "{Escape}")

    expect(screen.queryByRole("dialog")).not.toBeInTheDocument()
  })

  test("Controlled", async () => {
    render(<Controlled />)

    await userEvent.click(screen.getByText("Open Modal"))

    expect(await screen.findByRole("dialog")).toBeInTheDocument()
    expect(screen.getByText("Title content")).toBeInTheDocument()
    expect(screen.getByText("Body content")).toBeInTheDocument()

    await userEvent.click(screen.getByLabelText("Close"))

    expect(screen.queryByRole("dialog")).not.toBeInTheDocument()
  })

  test("InitiallyOpen", async () => {
    render(<InitiallyOpen />)

    expect(await screen.findByRole("dialog")).toBeInTheDocument()
    expect(screen.getByText("Title content")).toBeInTheDocument()
    expect(screen.getByText("Body content")).toBeInTheDocument()
  })
})
