import '@testing-library/jest-dom'

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

import { PktSelect } from './Select'

expect.extend(toHaveNoViolations)

describe('PktSelect', () => {
  test('renders select field with correct props', async () => {
    const { container } = render(
      <PktSelect label="Input Label" id="inputIdeas" ariaLabelledby="inputId">
        <option>Oslosommer</option>
      </PktSelect>,
    )

    const select = container.querySelector('#inputIdeas-input') as HTMLSelectElement | null
    expect(select).toBeInTheDocument()
    expect(select).toHaveAttribute('id', 'inputIdeas-input')
    expect(select?.tagName).toBe('SELECT')
    expect(select?.id).toBe('inputIdeas-input')

    const inputWrapper = container.querySelector('.pkt-inputwrapper') as HTMLDivElement | null
    expect(inputWrapper).toBeInTheDocument()
    expect(inputWrapper).toHaveTextContent('Input Label')

    const label = container.querySelector('label') as HTMLLabelElement | null
    expect(label).toBeInTheDocument()
    expect(label).toHaveAttribute('for', 'inputIdeas-input')
  })

  test('renders error message when hasError prop is true', async () => {
    render(
      <PktSelect label="Input Label" id="inputId" hasError errorMessage="Input error" />,
    )
    const alertContainer = screen.getByRole('alert')
    const errorMessageId = 'inputId-input-error' // når https://github.com/oslokommune/punkt/issues/3092 er fiksa:  screen.getByRole('combobox').getAttribute('aria-errormessage')
    expect(alertContainer).toHaveAttribute('id', errorMessageId)
    expect(alertContainer).toHaveTextContent('Input error')
  })

  describe('PktSelect', () => {
    test('toggles helptext class', async () => {
      const { getByText, container } = render(
        <PktSelect label="Input Label" id="inputId" helptext="Help Text" helptextDropdown="Help Text" />,
      )

      const expandButton = getByText('Les mer').closest('button') as HTMLButtonElement
      const helptextElement = container.querySelector('.pkt-inputwrapper__helptext-expandable-closed')

      await fireEvent.click(expandButton)
      expect(helptextElement).toHaveClass('pkt-inputwrapper__helptext-expandable-open')

      await fireEvent.click(expandButton)
      expect(helptextElement).toHaveClass('pkt-inputwrapper__helptext-expandable-closed')
    })
  })

  describe('accessibility', () => {
    it('renders with no wcag errors with axe', async () => {
      const { container } = render(<PktSelect label="Input Label" id="inputId" />)

      const results = await axe(container)
      expect(results).toHaveNoViolations()
    })
  })
})
