// Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

import { getNode } from '@formkit/core'
import { getAllByRole, getByRole, waitFor } from '@testing-library/vue'

import { renderComponent } from '#tests/support/components/index.ts'
import { mockApplicationConfig } from '#tests/support/mock-applicationConfig.ts'
import { waitForNextTick } from '#tests/support/utils.ts'

import { mockFormUpdaterQuery } from '#shared/components/Form/graphql/queries/formUpdater.mocks.ts'

import TimeAccountingFlyout from '../TimeAccountingFlyout.vue'

const renderTimeAccountingFlyout = async () => {
  const result = renderComponent(TimeAccountingFlyout, {
    form: true,
    flyout: true,
    router: true,
  })

  await getNode('ticket-time-accounting')?.settled

  await waitForNextTick()

  return result
}

// The activity type field is hidden in the schema and only revealed by the initial form
//   updater, so `show` is what decides whether it is rendered.
const mockTimeAccountingTypesFormUpdater = (show?: boolean) =>
  mockFormUpdaterQuery({
    formUpdater: {
      fields: {
        accounted_time_type_id: {
          show,
          value: 1,
          options: [
            {
              value: 1,
              label: 'test type 1',
            },
            {
              value: 2,
              label: 'test type 2',
            },
            {
              value: 3,
              label: 'test type 3',
            },
          ],
        },
      },
    },
  })

describe('TimeAccountingFlyout.vue', () => {
  beforeEach(() => {
    mockTimeAccountingTypesFormUpdater()
  })

  it('renders time accounting flyout', async () => {
    const wrapper = await renderTimeAccountingFlyout()

    expect(
      wrapper.getByRole('complementary', {
        name: 'Time accounting',
      }),
    ).toBeInTheDocument()

    expect(wrapper.getByRole('heading', { name: 'Time accounting' })).toBeInTheDocument()

    expect(wrapper.getByLabelText('Accounted time')).toBeInTheDocument()

    expect(wrapper.queryByText('hour(s)')).not.toBeInTheDocument()
    expect(wrapper.queryByLabelText('Activity type')).not.toBeInTheDocument()

    expect(wrapper.getByRole('button', { name: 'Skip' })).toBeInTheDocument()

    expect(wrapper.getByRole('button', { name: 'Account time' })).toBeInTheDocument()
  })

  it('can submit time accounting data', async () => {
    const wrapper = await renderTimeAccountingFlyout()

    await wrapper.events.click(wrapper.getByRole('button', { name: 'Account time' }))

    const input = wrapper.getByLabelText('Accounted time')

    expect(input).toBeDescribedBy('This field is required.')

    await wrapper.events.type(input, 'foo')

    await getNode('timeUnit')?.settled

    await wrapper.events.click(wrapper.getByRole('button', { name: 'Account time' }))

    expect(input).toBeDescribedBy('This field must contain a number.')

    await wrapper.events.clear(input)
    await wrapper.events.type(input, '-1.5')

    await getNode('timeUnit')?.settled

    await wrapper.events.click(wrapper.getByRole('button', { name: 'Account time' }))

    expect(wrapper.emitted('account-time')[0]).toEqual([
      {
        time_unit: '-1.5',
      },
    ])
  })

  it('can skip time accounting', async () => {
    const wrapper = await renderTimeAccountingFlyout()

    await wrapper.events.click(wrapper.getByRole('button', { name: 'Skip' }))

    expect(wrapper.emitted('skip')).toHaveLength(1)
  })

  it('supports displaying time accounting unit', async () => {
    mockApplicationConfig({
      time_accounting_unit: 'hour',
    })

    const wrapper = await renderTimeAccountingFlyout()

    expect(wrapper.queryByText('hour(s)')).toBeInTheDocument()
  })

  it('does not render the time accounting type selection if the form updater hides it', async () => {
    mockTimeAccountingTypesFormUpdater(false)

    const wrapper = await renderTimeAccountingFlyout()

    expect(wrapper.queryByLabelText('Activity type')).not.toBeInTheDocument()
  })

  it('supports optional time accounting type selection', async () => {
    mockTimeAccountingTypesFormUpdater(true)

    const wrapper = await renderTimeAccountingFlyout()

    const select = wrapper.getByLabelText('Activity type')

    // Default value set by form updater.
    expect(getNode('accountedTimeTypeId')?.value).toBe(1)

    await wrapper.events.click(select)

    const listbox = wrapper.getByRole('listbox')

    await wrapper.events.click(getAllByRole(listbox, 'option')[1])

    await wrapper.events.type(wrapper.getByLabelText('Accounted time'), '0')

    await getNode('timeUnit')?.settled

    await wrapper.events.click(wrapper.getByRole('button', { name: 'Account time' }))

    expect(wrapper.emitted('account-time')[0]).toEqual([
      {
        time_unit: '0',
        accounted_time_type_id: 2,
      },
    ])

    await wrapper.events.click(getByRole(select, 'button', { name: 'Clear selection' }))

    await wrapper.events.click(wrapper.getByRole('button', { name: 'Account time' }))

    expect(wrapper.emitted('account-time')[1]).toEqual([
      {
        time_unit: '0',
        accounted_time_type_id: null,
      },
    ])
  })

  it('should autofocus accounted time on mounted', async () => {
    const wrapper = await renderTimeAccountingFlyout()

    await waitForNextTick()

    await waitFor(() =>
      expect(wrapper.getByPlaceholderText('Enter the time you want to record')).toHaveFocus(),
    )
  })

  it('supports time unit separated by coma and converts it to float', async () => {
    const wrapper = await renderTimeAccountingFlyout()

    const input = wrapper.getByLabelText('Accounted time')

    await wrapper.events.type(input, '1,5')

    await getNode('timeUnit')?.settled

    await wrapper.events.click(wrapper.getByRole('button', { name: 'Account time' }))

    // The hidden activity type field contributes no value, even though the form updater
    //   provided a default one.
    expect(wrapper.emitted('account-time')[0]).toEqual([
      {
        time_unit: '1.5',
      },
    ])
  })
})
