import '@testing-library/jest-dom'

import { fireEvent, render } from '@testing-library/react'
import { axe, toHaveNoViolations } from 'jest-axe'
import { vi } from 'vitest'

import { PktInputWrapper } from '../inputwrapper/InputWrapper'
import { PktRadioButton } from './RadioButton'

expect.extend(toHaveNoViolations)

describe('PktRadiobutton', () => {
  // Test case for rendering a basic radiogroup
  it('renders without errors', async () => {
    const { container } = render(<PktRadioButton id="radio1" name="radioGroup" label="Option 1" value="option1" />)

    const inputElement = container.querySelector('input[type="radio"]')
    expect(inputElement).toBeInTheDocument()
    expect(inputElement).toHaveAttribute('id', 'radio1')
    expect(inputElement).toHaveAttribute('name', 'radioGroup')
    expect(inputElement).toHaveAttribute('value', 'option1')
  })

  it('allows selecting one option from the group', async () => {
    const handleChange = vi.fn()
    const { container } = render(
      <PktInputWrapper forId="radioGroup" label="Etikett" hasFieldset>
        <PktRadioButton
          id="radio1"
          name="radioGroup"
          label="Option 1"
          value="option1"
          checked
          onChange={handleChange}
        />
        <PktRadioButton id="radio2" name="radioGroup" label="Option 2" value="option2" onChange={handleChange} />
      </PktInputWrapper>,
    )

    const option1 = container.querySelector('input[type="radio"][id="radio1"]')
    const option2 = container.querySelector('input[type="radio"][id="radio2"]')

    expect(option1).toBeInTheDocument()
    expect(option2).toBeInTheDocument()

    const changeHandler = vi.fn()
    option2?.addEventListener('change', changeHandler)

    // Manually dispatch a change event
    option2?.dispatchEvent(new CustomEvent('change', { detail: { value: 'option2' }, bubbles: true }))

    // Ensure event was fired
    expect(changeHandler).toHaveBeenCalled()
    expect(changeHandler.mock.calls[0][0].detail).toEqual({ value: 'option2' })
  })

  describe('accessibility', () => {
    it('renders with no wcag errors with axe', async () => {
      const { container } = render(
        <PktRadioButton name="accessibilitytest" id="accessibilityTest" label="My checkkbox" />,
      )

      const results = await axe(container)

      expect(results).toHaveNoViolations()
    })
  })
})
