import React from "react"
import { render, cleanup, fireEvent } from "@testing-library/react"
import "@testing-library/jest-dom/extend-expect"
import confirm from "../confirm"

function TestConfirm({ message, callback }) {
  const handleClick = async () => {
    const result = await confirm(message, { confirm: "Yep", cancel: "Nope" })
    callback(result)
  }

  return <button onClick={handleClick}>Delete</button>
}

afterEach(cleanup)
describe("confirm", () => {
  it("should return true when confirmed", () => {
    return new Promise(done => {
      const callback = result => {
        expect(result).toBe(true)
        done()
      }

      const { getByText } = render(
        <TestConfirm
          message="Are you sure?"
          confirm="Yep"
          cancel="nope"
          callback={callback}
        />
      )

      const deleteButton = getByText("Delete")

      fireEvent.click(deleteButton)

      const confirmButton = getByText("Yep")
      fireEvent.click(confirmButton)
    })
  })

  it("should return false when cancelled", () => {
    return new Promise(done => {
      const callback = result => {
        expect(result).toBe(false)
        done()
      }

      const { getByText } = render(
        <TestConfirm
          message="Are you sure?"
          confirm="Yep"
          cancel="nope"
          callback={callback}
        />
      )

      const deleteButton = getByText("Delete")

      fireEvent.click(deleteButton)

      const cancelButton = getByText("Nope")
      fireEvent.click(cancelButton)
    })
  })
})
