import { render, screen, waitFor } from '@testing-library/react'
import { vi } from 'vitest'
import Dashboard from '../Dashboard'
import { documentService } from '../../services/api'

// Mock the document service directly
const mockDocumentService = vi.mocked(documentService, true)

// Mock the NotificationContext
vi.mock('../../contexts/NotificationContext', () => ({
  useNotifications: () => ({
    addNotification: vi.fn(),
    removeNotification: vi.fn(),
    clearNotifications: vi.fn(),
    notifications: [],
  }),
}))

// Mock child components
vi.mock('../FileUpload', () => ({
  default: ({ onUploadSuccess }: any) => (
    <div data-testid="file-upload">File Upload Component</div>
  ),
}))

vi.mock('../DocumentList', () => ({
  default: ({ documents, loading }: any) => (
    <div data-testid="document-list">
      {loading ? 'Loading...' : `${documents.length} documents`}
    </div>
  ),
}))

vi.mock('../SearchBar', () => ({
  default: ({ onSearch }: any) => (
    <input
      data-testid="search-bar"
      placeholder="Search"
      onChange={(e) => onSearch(e.target.value)}
    />
  ),
}))

const mockDocuments = [
  {
    id: '1',
    filename: 'test1.pdf',
    original_filename: 'test1.pdf',
    file_size: 1024,
    mime_type: 'application/pdf',
    tags: [],
    created_at: '2023-01-01T00:00:00Z',
    has_ocr_text: true,
  },
  {
    id: '2',
    filename: 'test2.txt',
    original_filename: 'test2.txt',
    file_size: 512,
    mime_type: 'text/plain',
    tags: ['important'],
    created_at: '2023-01-02T00:00:00Z',
    has_ocr_text: false,
  },
]

describe('Dashboard', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  test('renders dashboard with file upload and document list', async () => {
    render(<Dashboard />)

    expect(screen.getByText('Document Management')).toBeInTheDocument()
    expect(screen.getByText('Drag & drop a file here, or click to select')).toBeInTheDocument()
    expect(screen.getByPlaceholderText('Search documents...')).toBeInTheDocument()
    
    await waitFor(() => {
      expect(screen.getByText('Loading documents...')).toBeInTheDocument()
    })
  })

  test('handles loading state', () => {
    render(<Dashboard />)

    // Should render the main elements
    expect(screen.getByText('Document Management')).toBeInTheDocument()
  })

  test('renders search functionality', async () => {
    render(<Dashboard />)

    // Check that search components are rendered
    const searchInput = screen.getByPlaceholderText('Search documents...')
    const searchButton = screen.getByText('Search')
    expect(searchInput).toBeInTheDocument()
    expect(searchButton).toBeInTheDocument()
  })
})