import { describe, it, expect, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import FeedbackButtons from '@/components/feedback/FeedbackButtons.vue'

const defaultProps = {
  alertId: 'alert-1',
  alertType: 'SepsisWarning',
  severity: 'Critical',
}

function ratingButtons(wrapper) {
  return wrapper.findAll('[role="radio"]')
}

function ratingButton(wrapper, label) {
  return ratingButtons(wrapper).find(b => b.text() === label)
}

describe('FeedbackButtons', () => {
  beforeEach(() => {
    localStorage.clear()
    setActivePinia(createPinia())
  })

  it('rendersAllSixRatingButtons', () => {
    const wrapper = mount(FeedbackButtons, { props: defaultProps })
    expect(ratingButtons(wrapper)).toHaveLength(6)
  })

  it('selectingRatingHighlightsButton', async () => {
    const wrapper = mount(FeedbackButtons, { props: defaultProps })
    const usefulBtn = ratingButton(wrapper, 'Useful')

    await usefulBtn.trigger('click')

    expect(usefulBtn.classes()).toContain('ring-2')
    expect(usefulBtn.classes()).toContain('bg-green-100')
  })

  it('showNotesFieldOnPlusNote', async () => {
    const wrapper = mount(FeedbackButtons, { props: defaultProps })
    await ratingButton(wrapper, 'Useful').trigger('click')

    const noteBtn = wrapper.findAll('button').find(b => b.text() === '+ Note')
    await noteBtn.trigger('click')

    expect(wrapper.find('input').exists()).toBe(true)
  })

  it('ariaCheckedOnSelectedRating', async () => {
    const wrapper = mount(FeedbackButtons, { props: defaultProps })
    const usefulBtn = ratingButton(wrapper, 'Useful')
    const fpBtn = ratingButton(wrapper, 'False positive')

    await usefulBtn.trigger('click')

    expect(usefulBtn.attributes('aria-checked')).toBe('true')
    expect(fpBtn.attributes('aria-checked')).toBe('false')
  })

  it('keyboardNavigationWorks', async () => {
    const wrapper = mount(FeedbackButtons, { props: defaultProps })
    const buttons = ratingButtons(wrapper)

    expect(buttons.every(b => b.element.tagName === 'BUTTON')).toBe(true)

    await ratingButton(wrapper, 'Useful').trigger('click')
    expect(ratingButton(wrapper, 'Useful').attributes('aria-checked')).toBe('true')

    await ratingButton(wrapper, 'Too early').trigger('click')
    expect(ratingButton(wrapper, 'Too early').attributes('aria-checked')).toBe('true')
    expect(ratingButton(wrapper, 'Useful').attributes('aria-checked')).toBe('false')

    const noteBtn = wrapper.findAll('button').find(b => b.text() === '+ Note')
    await noteBtn.trigger('click')

    const input = wrapper.get('input')
    await input.setValue('Expected after metoprolol')
    await input.trigger('keydown.enter')

    expect(wrapper.find('input').exists()).toBe(false)
  })
})
