import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import Savings from '../pages/Savings'
import { useAuthStore } from '../store/auth'

vi.mock('../store/auth', () => ({
  useAuthStore: vi.fn(),
}))

vi.mock('../api/savings', () => ({
  savingsApi: {
    listCategories: vi.fn(),
    getStats: vi.fn(),
    listTransactions: vi.fn(),
    createCategory: vi.fn(),
    updateCategory: vi.fn(),
    deleteCategory: vi.fn(),
    createTransaction: vi.fn(),
    deleteTransaction: vi.fn(),
    getMembers: vi.fn(),
    getRecurringPlans: vi.fn(),
  },
}))

vi.mock('../components/Navigation', () => ({
  default: () => <nav data-testid="navigation">Nav</nav>,
}))

import { savingsApi } from '../api/savings'

const mockCategories = [
  { id: 1, name: 'Квартира', target_amount: 500000, current_amount: 100000, color: '#6366f1', emoji: '🏠', is_shared: false },
]

const mockStats = {
  total_balance: 100000,
  categories_count: 1,
  total_deposited: 150000,
  total_withdrawn: 50000,
}

const renderSavings = () => {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
  return render(
    <QueryClientProvider client={qc}>
      <MemoryRouter>
        <Savings />
      </MemoryRouter>
    </QueryClientProvider>
  )
}

describe('Savings page', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    useAuthStore.mockImplementation((selector) => selector({ user: { id: 1 } }))
    savingsApi.listCategories.mockResolvedValue(mockCategories)
    savingsApi.getStats.mockResolvedValue(mockStats)
    savingsApi.listTransactions.mockResolvedValue([])
    savingsApi.getMembers.mockResolvedValue([])
    savingsApi.getRecurringPlans.mockResolvedValue([])
  })

  it('renders savings page', async () => {
    renderSavings()
    await waitFor(() => {
      expect(screen.getByText('Накопления')).toBeInTheDocument()
    })
  })

  it('renders navigation', () => {
    renderSavings()
    expect(screen.getByTestId('navigation')).toBeInTheDocument()
  })

  it('renders categories', async () => {
    renderSavings()
    await waitFor(() => {
      expect(screen.getByText('Квартира')).toBeInTheDocument()
    })
  })

  it('renders tab navigation', async () => {
    renderSavings()
    await waitFor(() => {
      expect(screen.getByText('Обзор')).toBeInTheDocument()
    })
  })
})
