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

vi.mock('recharts', () => ({
  LineChart: ({ children }) => <div data-testid="line-chart">{children}</div>,
  Line: () => <div />,
  BarChart: ({ children }) => <div data-testid="bar-chart">{children}</div>,
  Bar: () => <div />,
  XAxis: () => <div />,
  YAxis: () => <div />,
  Tooltip: () => <div />,
  ResponsiveContainer: ({ children }) => <div>{children}</div>,
  Cell: () => <div />,
  Area: () => <div />,
  AreaChart: ({ children }) => <div data-testid="area-chart">{children}</div>,
  CartesianGrid: () => <div />,
}))

vi.mock('../api/habits', () => ({
  habitsApi: {
    list: vi.fn(),
    getStats: vi.fn(),
    getLogs: vi.fn(),
  },
}))

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

import { habitsApi } from '../api/habits'

const mockStats = {
  total_habits: 3,
  total_logs: 45,
  current_streak: 7,
  best_streak: 14,
  completion_rate: 82,
  habits: [
    { id: 1, name: 'Exercise', completion_rate: 90, streak: 7 },
    { id: 2, name: 'Read', completion_rate: 75, streak: 3 },
  ],
  daily_completions: [
    { date: '2026-03-01', count: 2 },
    { date: '2026-03-02', count: 3 },
  ],
}

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

describe('Stats page', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    habitsApi.list.mockResolvedValue([])
    habitsApi.getStats.mockResolvedValue(mockStats)
    habitsApi.getLogs.mockResolvedValue([])
  })

  it('renders stats page', async () => {
    renderStats()
    await waitFor(() => {
      expect(screen.getByText('Статистика')).toBeInTheDocument()
    })
  })

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

  it('shows habit selector', async () => {
    habitsApi.list.mockResolvedValue([
      { id: 1, name: 'Exercise', color: '#6366f1', icon: '💪' },
    ])
    renderStats()
    // Open dropdown to see habit names
    await waitFor(() => {
      // Click the habit selector button to open dropdown
      const selectorBtn = document.querySelector('button.w-full')
      if (selectorBtn) fireEvent.click(selectorBtn)
    })
    await waitFor(() => {
      expect(screen.getByText('Exercise')).toBeInTheDocument()
    })
  })
})
