import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import CoverSheetView from '@/views/CoverSheetView.vue'

vi.mock('@/api/client', () => ({
  get: vi.fn(),
  post: vi.fn(),
  postBlob: vi.fn(),
}))

vi.mock('@/composables/useToast', () => ({
  useToast: () => ({
    success: vi.fn(),
    error: vi.fn(),
  }),
}))

vi.mock('@/components/AppHeader.vue', () => ({
  default: { template: '<div />' },
}))

vi.mock('@/components/PatientSearch.vue', () => ({
  default: {
    props: ['modelValue'],
    emits: ['update:modelValue'],
    template: '<input data-testid="patient-search" />',
  },
}))

import { get, post } from '@/api/client'

const mockedGet = vi.mocked(get)
const mockedPost = vi.mocked(post)

beforeEach(() => {
  setActivePinia(createPinia())
  vi.clearAllMocks()

  mockedGet.mockImplementation(async (url: string) => {
    if (url === 'users') {
      return {
        success: true,
        statusCode: 200,
        data: [{ id: 'clerk-1', username: 'entry1', fullName: 'Entry Clerk', role: 'DATA_ENTRY_CLERK' }],
        error: null,
      }
    }
    if (url === 'cover-sheets') {
      return {
        success: true,
        statusCode: 200,
        data: [
          {
            id: 'cs-1',
            code: 'VCR-CS-AABBCCDD',
            batchType: 'VITALS_SHEET',
            track: 'BACKFILL',
            patientId: null,
            patientName: null,
            patientMrn: null,
            assignToUserId: null,
            assignToUserName: null,
            isUsed: false,
            batchId: null,
            createdAt: '2026-06-27T12:00:00Z',
            usedAt: null,
          },
        ],
        error: null,
      }
    }
    return { success: true, statusCode: 200, data: [], error: null }
  })
})

describe('CoverSheetView', () => {
  it('renders generate form and cover sheet list', async () => {
    const wrapper = mount(CoverSheetView)
    await flushPromises()

    expect(wrapper.text()).toContain('Generate Cover Sheets')
    expect(wrapper.text()).toContain('Cover Sheet List')
    expect(wrapper.text()).toContain('VCR-CS-AABBCCDD')
    expect(wrapper.find('select').exists()).toBe(true)
  })

  it('loads entry clerks and cover sheets on mount', async () => {
    mount(CoverSheetView)
    await flushPromises()

    expect(mockedGet).toHaveBeenCalledWith('users', { role: 'DATA_ENTRY_CLERK' })
    expect(mockedGet).toHaveBeenCalledWith('cover-sheets', expect.objectContaining({
      page: 1,
      pageSize: 20,
    }))
  })

  it('submits generate request with form values', async () => {
    mockedPost.mockResolvedValueOnce({
      success: true,
      statusCode: 201,
      data: [{ id: 'new-cs-1', code: 'VCR-CS-NEW12345' }],
      error: null,
    })

    const wrapper = mount(CoverSheetView)
    await flushPromises()

    const batchTypeSelect = wrapper.findAll('select')[0]
    await batchTypeSelect.setValue('VITALS_SHEET')

    const countInput = wrapper.find('input[type="number"]')
    await countInput.setValue(5)

    await wrapper.find('form').trigger('submit.prevent')
    await flushPromises()

    expect(mockedPost).toHaveBeenCalledWith('cover-sheets/generate', {
      count: 5,
      batchType: 'VITALS_SHEET',
      track: 'BACKFILL',
    })
  })

  it('shows Print Cover Sheets after successful generation', async () => {
    mockedPost.mockResolvedValueOnce({
      success: true,
      statusCode: 201,
      data: [
        { id: 'new-cs-1', code: 'VCR-CS-NEW12345' },
        { id: 'new-cs-2', code: 'VCR-CS-NEW67890' },
      ],
      error: null,
    })

    const wrapper = mount(CoverSheetView)
    await flushPromises()

    await wrapper.findAll('select')[0].setValue('LAB_RESULTS')
    await wrapper.find('form').trigger('submit.prevent')
    await flushPromises()

    expect(wrapper.text()).toContain('Print Cover Sheets')
  })
})
