import { render, screen, waitFor } from '@testing-library/react'
import { describe, it, expect, vi } from 'vitest'
import { BrowserRouter } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import LogsPage from '@/pages/LogsPage'
import * as logsApi from '@/api/logsApi'
import * as entitiesApi from '@/api/entitiesApi'

vi.mock('@/api/logsApi')
vi.mock('@/api/entitiesApi')

const wrapper = ({ children }: { children: React.ReactNode }) => (
  <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
    <BrowserRouter>{children}</BrowserRouter>
  </QueryClientProvider>
)

const mockLog = {
  id: 'log-1',
  entityId: 'e1',
  entityName: 'Entity A',
  promptSent: 'prompt',
  aiResponse: 'response',
  emailSubject: 'Weekly Memo',
  emailBody: 'Dear colleagues',
  status: 'SENT' as const,
  errorMessage: null,
  dispatchedAt: '2024-01-01T10:00:00',
}

describe('LogsPage', () => {
  it('should_renderLogTable_when_logsLoaded', async () => {
    vi.mocked(logsApi.getLogs).mockResolvedValue([mockLog])
    vi.mocked(entitiesApi.getEntities).mockResolvedValue([])
    render(<LogsPage />, { wrapper })
    await waitFor(() => {
      expect(screen.getByText('Weekly Memo')).toBeInTheDocument()
    })
  })

  it('should_renderDarkModeStyles_when_pageLoads', async () => {
    vi.mocked(logsApi.getLogs).mockResolvedValue([mockLog])
    vi.mocked(entitiesApi.getEntities).mockResolvedValue([])

    render(<LogsPage />, { wrapper })

    await waitFor(() => {
      expect(screen.getByRole('heading', { name: /dispatch logs/i })).toHaveClass('text-slate-100')
      expect(screen.getByRole('combobox')).toHaveClass('border-slate-700', 'bg-slate-800', 'text-slate-100')
      expect(screen.getByText('Weekly Memo')).toHaveClass('text-slate-100')
    })
  })

  it('should_filterLogsByEntity_when_filterSelected', async () => {
    vi.mocked(logsApi.getLogs).mockResolvedValue([mockLog])
    vi.mocked(entitiesApi.getEntities).mockResolvedValue([
      { id: 'e1', name: 'Entity A', email: 'a@a.com', jobTitle: 'Job', personality: '', scheduleCron: '', contextWindowDays: 3, active: true, createdAt: '' },
    ])
    render(<LogsPage />, { wrapper })
    await waitFor(() => {
      expect(screen.getByText('Weekly Memo')).toBeInTheDocument()
    })
    expect(screen.getByRole('combobox', { hidden: true })).toBeInTheDocument()
  })
})
