import { describe, it, expect, beforeEach } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import { http, HttpResponse } from 'msw'
import { server } from '@/test/mocks/server'
import { renderWithProviders } from '@/test/utils'
import { ReportsPage } from '@/pages/ReportsPage'

describe('ReportsPage', () => {
  beforeEach(() => {
    localStorage.setItem('access_token', 'test-token')
  })

  it('renders report list with report metadata', async () => {
    renderWithProviders(<ReportsPage />, { initialRoute: '/reports' })

    await waitFor(() => {
      // mockReportMeta has jahr: 2026, kw: 6
      expect(screen.getByText('2026')).toBeInTheDocument()
    })

    expect(screen.getByText('KW 6')).toBeInTheDocument()

    // Total count should show in the header "Bisherige Berichte (1)"
    expect(screen.getByText('Bisherige Berichte (1)')).toBeInTheDocument()
  })

  it('shows "Bericht generieren" button and form fields', async () => {
    renderWithProviders(<ReportsPage />, { initialRoute: '/reports' })

    await waitFor(() => {
      // "Bericht generieren" appears as card title and button text; use button role
      expect(screen.getByRole('button', { name: /Bericht generieren/ })).toBeInTheDocument()
    })

    // Admin user sees the generation form with Jahr and KW inputs
    expect(screen.getByLabelText('Jahr')).toBeInTheDocument()
    expect(screen.getByLabelText('Kalenderwoche')).toBeInTheDocument()
  })

  it('handles empty report list', async () => {
    server.use(
      http.get('/api/reports/list', () => {
        return HttpResponse.json({ items: [], total: 0 })
      }),
    )

    renderWithProviders(<ReportsPage />, { initialRoute: '/reports' })

    await waitFor(() => {
      expect(screen.getByText('Keine Berichte vorhanden.')).toBeInTheDocument()
    })
  })

  it('shows loading state', () => {
    server.use(
      http.get('/api/reports/list', async () => {
        await new Promise((resolve) => setTimeout(resolve, 500))
        return HttpResponse.json({ items: [], total: 0 })
      }),
    )

    renderWithProviders(<ReportsPage />, { initialRoute: '/reports' })

    // The heading is always visible
    expect(screen.getByText('Berichte')).toBeInTheDocument()

    // During loading, the empty state message or report data should not be visible
    expect(screen.queryByText('Keine Berichte vorhanden.')).not.toBeInTheDocument()
    expect(screen.queryByText('KW 6')).not.toBeInTheDocument()
  })

  it('shows error on API failure', async () => {
    server.use(
      http.get('/api/reports/list', () => {
        return new HttpResponse(null, { status: 500 })
      }),
    )

    renderWithProviders(<ReportsPage />, { initialRoute: '/reports' })

    // When query fails, reports defaults to [] so empty state appears
    await waitFor(() => {
      expect(screen.getByText('Keine Berichte vorhanden.')).toBeInTheDocument()
    })
  })
})
