import '@testing-library/jest-dom'

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

import { PktTextarea } from './Textarea'

expect.extend(toHaveNoViolations)

describe('PktTextarea', () => {
  test('renders input field with correct props', async () => {
    const { getByLabelText } = render(<PktTextarea label="Input Label" id="inputId" />)

    const inputElement = getByLabelText('Input Label')
    expect(inputElement).toBeInTheDocument()
    expect(inputElement.tagName).toBe('TEXTAREA')
    expect(inputElement.id).toBe('inputId-input')
  })

  test('renders error message when hasError prop is true', async () => {
    const { getByText } = render(<PktTextarea 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')
  })

  describe('PktTextarea', () => {
    test('toggles helptext class', async () => {
      const { getByText, container } = render(
        <PktTextarea 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(<PktTextarea label="Input Label" id="inputId" />)
      await window.customElements.whenDefined('pkt-textarea')
      const results = await axe(container)
      expect(results).toHaveNoViolations()
    })
  })
})
