import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import TransactionList from '../components/finance/TransactionList'

vi.mock('../api/finance', () => ({
  financeApi: {
    listCategories: vi.fn(),
    listTransactions: vi.fn(),
    deleteTransaction: vi.fn(),
  },
}))

import { financeApi } from '../api/finance'

const mockCategories = [
  { id: 1, name: 'Еда', type: 'expense', emoji: '🍔' },
]

const mockTransactions = [
  { id: 1, amount: 500, type: 'expense', category_id: 1, description: 'Продукты', date: '2026-03-15T00:00:00Z' },
  { id: 2, amount: 1000, type: 'income', category_id: null, description: 'Зарплата', date: '2026-03-01T00:00:00Z' },
]

describe('TransactionList', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    financeApi.listCategories.mockResolvedValue(mockCategories)
    financeApi.listTransactions.mockResolvedValue(mockTransactions)
  })

  const renderList = () =>
    render(<TransactionList onAdd={vi.fn()} month={3} year={2026} />)

  it('shows loading state initially', () => {
    financeApi.listCategories.mockReturnValue(new Promise(() => {}))
    financeApi.listTransactions.mockReturnValue(new Promise(() => {}))
    renderList()
    const loadingDivs = document.querySelectorAll('.animate-pulse')
    expect(loadingDivs.length).toBeGreaterThan(0)
  })

  it('shows transactions after loading', async () => {
    renderList()
    await waitFor(() => {
      expect(screen.getByText('Продукты')).toBeInTheDocument()
    })
  })

  it('shows income transaction', async () => {
    renderList()
    await waitFor(() => {
      expect(screen.getByText('Зарплата')).toBeInTheDocument()
    })
  })

  it('renders filter buttons', async () => {
    renderList()
    await waitFor(() => {
      // There are two "Все" buttons (type filter and category filter), use getAllByText
      const allButtons = screen.getAllByText('Все')
      expect(allButtons.length).toBeGreaterThan(0)
      expect(screen.getByText('Расходы')).toBeInTheDocument()
      expect(screen.getByText('Доходы')).toBeInTheDocument()
    })
  })
})
