import { useQuery } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import SnippetTagsFilter from '../snippet-tags-filter'

vi.mock('@tanstack/react-query', () => ({
  useQuery: vi.fn(),
}))

vi.mock('@/service/client', () => ({
  consoleQuery: {
    tags: {
      get: {
        queryOptions: vi.fn((input) => ({ queryKey: ['tags', input] })),
      },
    },
  },
}))

const mockUseQuery = vi.mocked(useQuery)

describe('SnippetTagsFilter', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    mockUseQuery.mockReturnValue({
      data: [
        { id: 'tag-1', name: 'Sales', type: 'snippet', binding_count: '' },
        { id: 'tag-2', name: 'Support', type: 'snippet', binding_count: '' },
      ],
    } as ReturnType<typeof useQuery>)
  })

  it('should show selected tag count and update selected tags', async () => {
    const user = userEvent.setup()
    const onChange = vi.fn()

    render(<SnippetTagsFilter embedded value={['tag-1']} onChange={onChange} />)

    await user.click(screen.getByRole('button', { name: 'Sales' }))

    expect(screen.getByText('1')).toBeInTheDocument()

    await user.click(screen.getByText('Support'))

    expect(onChange).toHaveBeenCalledWith(['tag-1', 'tag-2'], expect.anything())
  })

  it('should filter tags by search text and show an empty state', async () => {
    const user = userEvent.setup()

    render(<SnippetTagsFilter value={[]} onChange={vi.fn()} />)

    const trigger = screen.getByRole('button', { name: 'common.tag.placeholder' })
    trigger.focus()
    await user.keyboard('{Enter}')
    const search = screen.getByRole('textbox', { name: 'pluginTags.searchTags' })
    await user.type(search, 'sup')

    expect(screen.getByText('Support')).toBeInTheDocument()
    expect(screen.queryByText('Sales')).not.toBeInTheDocument()

    await user.clear(search)
    await user.type(search, 'missing')

    expect(screen.getByText('common.tag.noTag')).toBeInTheDocument()
  })

  it('resets the transient tag search after the popover closes', async () => {
    const user = userEvent.setup()

    render(<SnippetTagsFilter value={[]} onChange={vi.fn()} />)

    const trigger = screen.getByRole('button', { name: 'common.tag.placeholder' })
    await user.click(trigger)
    expect(screen.getByRole('dialog', { name: 'common.tag.placeholder' })).toBeInTheDocument()
    await user.type(screen.getByRole('textbox', { name: 'pluginTags.searchTags' }), 'sup')
    expect(screen.queryByText('Sales')).not.toBeInTheDocument()

    await user.keyboard('{Escape}')
    await user.click(trigger)

    expect(screen.getByText('Sales')).toBeInTheDocument()
    expect(screen.getByText('Support')).toBeInTheDocument()
  })
})
