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 { DisclosuresPage } from '@/pages/DisclosuresPage'

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

  it('renders disclosure requests list', async () => {
    renderWithProviders(<DisclosuresPage />)

    await waitFor(() => {
      // The mock handler returns [mockDisclosureRequest] with fall_id '2026-06-onko-A123456789'
      expect(screen.getByText('2026-06-onko-A123456789')).toBeInTheDocument()
    })

    // Should show requester username
    expect(screen.getByText('dak_user')).toBeInTheDocument()

    // Should show the reason
    expect(screen.getByText('Benötige vollständige Patientendaten für Rückruf.')).toBeInTheDocument()

    // Should show the status badge (translated) — multiple "Ausstehend" exist (tab + badge)
    const badges = screen.getAllByText('Ausstehend')
    expect(badges.length).toBeGreaterThanOrEqual(1)
  })

  it('shows approve and reject buttons', async () => {
    renderWithProviders(<DisclosuresPage />)

    await waitFor(() => {
      expect(screen.getByText('Genehmigen')).toBeInTheDocument()
    })

    expect(screen.getByText('Ablehnen')).toBeInTheDocument()
  })

  it('handles empty disclosure list', async () => {
    server.use(
      http.get('/api/admin/disclosure-requests', () => {
        return HttpResponse.json([])
      }),
    )

    renderWithProviders(<DisclosuresPage />)

    await waitFor(() => {
      expect(screen.getByText('Keine Anfragen gefunden.')).toBeInTheDocument()
    })
  })

  it('shows loading state', () => {
    // Delay the API response to observe loading state
    server.use(
      http.get('/api/admin/disclosure-requests', async () => {
        await new Promise((resolve) => setTimeout(resolve, 500))
        return HttpResponse.json([])
      }),
    )

    renderWithProviders(<DisclosuresPage />)

    // The heading is always visible
    expect(screen.getByText('Freigabe-Anfragen')).toBeInTheDocument()

    // During loading, the empty message should not be visible yet
    expect(screen.queryByText('Keine Anfragen gefunden.')).not.toBeInTheDocument()
    // Nor should any disclosure item be visible
    expect(screen.queryByText('Genehmigen')).not.toBeInTheDocument()
  })
})
