import { describe, it, expect, vi } from 'vitest'

import { renderWithProviders, screen, userEvent } from '../../test/utils'

import ActionButton from '.'

describe('ActionButton', () => {
  describe('Rendering', () => {
    it('renders with children text', () => {
      renderWithProviders(<ActionButton>Click me</ActionButton>)
      expect(
        screen.getByRole('button', { name: 'Click me' })
      ).toBeInTheDocument()
    })
  })

  describe('Disabled State', () => {
    it('is disabled when disabled prop is true', () => {
      renderWithProviders(<ActionButton disabled>Disabled</ActionButton>)
      const button = screen.getByRole('button')
      expect(button).toBeDisabled()
    })

    it('does not trigger onClick when disabled', async () => {
      const handleClick = vi.fn()
      const user = userEvent.setup()

      renderWithProviders(
        <ActionButton disabled onClick={handleClick}>
          Disabled
        </ActionButton>
      )

      const button = screen.getByRole('button')
      await user.click(button)

      expect(handleClick).not.toHaveBeenCalled()
    })
  })

  describe('Click Handling', () => {
    it('calls onClick when clicked', async () => {
      const handleClick = vi.fn()
      const user = userEvent.setup()

      renderWithProviders(
        <ActionButton onClick={handleClick}>Click me</ActionButton>
      )

      const button = screen.getByRole('button')
      await user.click(button)

      expect(handleClick).toHaveBeenCalledTimes(1)
    })
  })

  describe('Type Attribute', () => {
    it('has button type by default', () => {
      renderWithProviders(<ActionButton>Default Type</ActionButton>)
      const button = screen.getByRole('button')
      expect(button).toHaveAttribute('type', 'button')
    })

    it('can have submit type', () => {
      renderWithProviders(<ActionButton type="submit">Submit</ActionButton>)
      const button = screen.getByRole('button')
      expect(button).toHaveAttribute('type', 'submit')
    })
  })

  describe('Accessibility', () => {
    it('is keyboard accessible', async () => {
      const handleClick = vi.fn()
      const user = userEvent.setup()

      renderWithProviders(
        <ActionButton onClick={handleClick}>Press me</ActionButton>
      )

      const button = screen.getByRole('button')
      button.focus()
      await user.keyboard('{Enter}')

      expect(handleClick).toHaveBeenCalledTimes(1)
    })

    it('can be focused', () => {
      renderWithProviders(<ActionButton>Focus me</ActionButton>)
      const button = screen.getByRole('button')
      button.focus()
      expect(button).toHaveFocus()
    })
  })
})
