import '@testing-library/jest-dom'

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

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 () => {
    const { getByText, getByRole } = render(
      <PktSelect label="Input Label" id="inputId" hasError errorMessage="Input error" />,
    )

    await window.customElements.whenDefined('pkt-alert')
    const errorMessage = getByText('Input error')
    expect(errorMessage).toBeInTheDocument()

    const alertContainer = errorMessage.closest('pkt-alert')
    expect(alertContainer).toHaveAttribute('id', 'inputId-input-error')
    expect(alertContainer).toHaveTextContent('Input error')

    const alert = getByRole('alert')
    expect(alert).toBeInTheDocument()
    expect(alert).toHaveAttribute('role', 'alert')
  })

  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()
    })
  })
})
