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

import { PktCalendar, IPktCalendar } from './Calendar'

expect.extend(toHaveNoViolations)

const createCalendar = (props: Partial<IPktCalendar> = {}) => {
  return render(<PktCalendar {...props} />)
}

describe('PktCalendar', () => {
  describe('Accessibility', () => {
    test('has no accessibility violations', async () => {
      const { container } = createCalendar({ withcontrols: true, weeknumbers: true })

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

    test('has proper ARIA attributes', () => {
      const { container } = createCalendar({ withcontrols: true })

      const calendarTable = container.querySelector('.pkt-calendar__body')
      expect(calendarTable).toHaveAttribute('role', 'grid')

      const dateButtons = container.querySelectorAll('.pkt-calendar__date')
      dateButtons.forEach((button) => {
        expect(button).toHaveAttribute('aria-pressed')
        expect(button).toHaveAttribute('tabindex')
      })
    })

    test('navigation buttons have proper labels', () => {
      const { container } = createCalendar({ withcontrols: true })

      const prevButton = container.querySelector('.pkt-calendar__prev-month')
      const nextButton = container.querySelector('.pkt-calendar__next-month')

      expect(prevButton).toHaveAttribute('aria-label')
      expect(nextButton).toHaveAttribute('aria-label')
    })

    test('date buttons have proper accessible names', () => {
      const { container } = createCalendar()

      const dateButtons = container.querySelectorAll('.pkt-calendar__date')
      dateButtons.forEach((button) => {
        expect(button).toHaveAttribute('aria-label')
        expect(button.getAttribute('aria-label')).toBeTruthy()
      })
    })

    test('selected dates have proper ARIA state', () => {
      const { container } = createCalendar()

      const firstDate = container.querySelector(
        '.pkt-calendar__date:not(.pkt-calendar__date--disabled)',
      )
      fireEvent.click(firstDate!)

      expect(firstDate).toHaveAttribute('aria-pressed', 'true')
    })

    test('disabled dates have proper ARIA state', () => {
      const { container } = createCalendar({ excludeweekdays: ['0', '6'] })

      const disabledDates = container.querySelectorAll('.pkt-calendar__date--disabled')
      disabledDates.forEach((date) => {
        expect(date).toHaveAttribute('disabled')
      })
    })
  })
})
