import * as React from 'react'
import { render, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'
import { CMultiSelectSelection } from '../CMultiSelectSelection'

const selected = [
  {
    label: 'text1',
    value: 'value1',
  },
  {
    label: 'text2',
    value: 'value2',
    disabled: true,
  },
]

test('loads and displays CMultiSelectSelection component', async () => {
  const { container } = render(<CMultiSelectSelection />)
  expect(container).toMatchSnapshot()
})

test('CMultiSelectSelection customize tags', async () => {
  const { container } = render(
    <CMultiSelectSelection
      multiple={true}
      search={true}
      selected={selected}
      selectionType="tags"
      selectionTypeCounterText="text"
    />,
  )
  expect(container).toMatchSnapshot()
  expect(container.firstChild).toHaveClass('form-multi-select-selection')
  const tags = container.querySelectorAll('.form-multi-select-tag')
  expect(tags.length).toBeGreaterThanOrEqual(2)
  const deleteBtn = container.querySelector('.form-multi-select-tag-delete')
  expect(deleteBtn).toBeInTheDocument()
})

test('CMultiSelectSelection customize counter', async () => {
  const { container } = render(
    <CMultiSelectSelection
      multiple={true}
      search={false}
      selected={selected}
      selectionType="counter"
      selectionTypeCounterText="text"
    />,
  )
  expect(container).toMatchSnapshot()
  expect(container.firstChild).toHaveClass('form-multi-select-selection')
  expect(container.firstChild).toHaveTextContent('2 text')
})

test('CMultiSelectSelection customize text', async () => {
  const { container } = render(
    <CMultiSelectSelection
      multiple={true}
      search={true}
      selected={selected}
      selectionType="text"
      selectionTypeCounterText="text"
    />,
  )
  expect(container).toMatchSnapshot()
  expect(container.firstChild).toHaveClass('form-multi-select-selection')
  expect(container.firstChild).toHaveTextContent('text1, text2')
})

test('CMultiSelectSelection test remove event', async () => {
  const onRemove = jest.fn()
  render(
    <CMultiSelectSelection
      multiple={true}
      selected={selected}
      selectionType="tags"
      onRemove={onRemove}
    />,
  )
  expect(onRemove).toHaveBeenCalledTimes(0)
  const removeButton = document.querySelector('.form-multi-select-tag-delete')
  if (removeButton !== null) {
    fireEvent.click(removeButton)
  }
  expect(onRemove).toHaveBeenCalledTimes(1)
})
