import React, { useState } from "react"
import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import "@testing-library/jest-dom/extend-expect"
import Modal, { Action } from "../"

describe("Modal", () => {
  test("actions render", () => {
    render(
      <Modal label="Label" onClose={() => {}}>
        Content
        <Action>Save</Action>
        <Action>Destroy</Action>
      </Modal>
    )

    expect(screen.getByText("Save")).toBeInTheDocument()
    expect(screen.getByText("Destroy")).toBeInTheDocument()
  })

  test("nested actions", () => {
    render(
      <Modal label="Label" onClose={() => {}}>
        Content
        <div>
          <Action>Save</Action>
          <Action>Destroy</Action>
        </div>
      </Modal>
    )

    expect(screen.getByText("Save")).toBeInTheDocument()
    expect(screen.getByText("Destroy")).toBeInTheDocument()

    const container = screen.getByTestId("actions")

    expect(container.contains(screen.getByText("Save"))).toBe(true)
    expect(container.contains(screen.getByText("Destroy"))).toBe(true)
  })

  test("no actions doesn't render container", () => {
    render(
      <Modal label="Label" onClose={() => {}}>
        Content
      </Modal>
    )

    expect(screen.queryByTestId("actions")).not.toBeInTheDocument()
  })

  test("handles changing props", () => {
    const TestModal = () => {
      const [token, setToken] = useState("primary")
      return (
        <Modal label="Label" onClose={() => {}}>
          Content
          <Action is={token} onClick={() => setToken("secondary")}>
            Change Color
          </Action>
          <Action>Destroy</Action>
        </Modal>
      )
    }

    render(<TestModal />)

    expect(
      screen.getByText("Change Color").className.includes("bg-red-500")
    ).toBe(true)

    userEvent.click(screen.getByText("Change Color"))

    expect(
      screen.getByText("Change Color").className.includes("bg-red-500")
    ).toBe(false)
  })
})
