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 Habits from '../pages/Habits'

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

vi.mock('../components/CreateHabitModal', () => ({
  default: ({ open, onClose }) => open ? (
    <div data-testid="create-habit-modal">
      <button onClick={onClose}>Close</button>
    </div>
  ) : null,
}))

vi.mock('../components/EditHabitModal', () => ({
  default: ({ open, onClose }) => open ? (
    <div data-testid="edit-habit-modal">
      <button onClick={onClose}>Close</button>
    </div>
  ) : null,
}))

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

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

const mockHabits = [
  { id: 1, name: 'Exercise', frequency: 'daily', color: '#6366f1', icon: '💪', is_archived: false, created_at: '2026-01-01T00:00:00Z' },
  { id: 2, name: 'Read', frequency: 'weekly', target_days: [1,2,3,4,5], color: '#22c55e', icon: '📚', is_archived: false, created_at: '2026-01-01T00:00:00Z' },
]

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

describe('Habits page', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    habitsApi.list.mockResolvedValue(mockHabits)
    habitsApi.getHabitStats.mockResolvedValue({ streak: 5, completion_rate: 80 })
  })

  it('renders habits list', async () => {
    renderHabits()
    await waitFor(() => {
      expect(screen.getByText('Exercise')).toBeInTheDocument()
      expect(screen.getByText('Read')).toBeInTheDocument()
    })
  })

  it('renders header when not embedded', async () => {
    renderHabits(false)
    await waitFor(() => {
      expect(screen.getByText('Мои привычки')).toBeInTheDocument()
    })
  })

  it('does not render header when embedded', async () => {
    renderHabits(true)
    await waitFor(() => {
      expect(screen.queryByText('Мои привычки')).not.toBeInTheDocument()
    })
  })

  it('opens create habit modal', async () => {
    renderHabits()
    await waitFor(() => {
      expect(screen.getByText('Мои привычки')).toBeInTheDocument()
    })
    fireEvent.click(screen.getByText('Новая'))
    expect(screen.getByTestId('create-habit-modal')).toBeInTheDocument()
  })

  it('renders navigation when not embedded', () => {
    renderHabits(false)
    expect(screen.getByTestId('navigation')).toBeInTheDocument()
  })

  it('shows empty state when no habits', async () => {
    habitsApi.list.mockResolvedValue([])
    renderHabits()
    await waitFor(() => {
      expect(screen.getByText(/Нет привычек/)).toBeInTheDocument()
    })
  })
})
