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 CreateHabitModal from '../components/CreateHabitModal'

vi.mock('../api/client', () => ({
  default: {
    post: vi.fn(),
    get: vi.fn(),
    put: vi.fn(),
    delete: vi.fn(),
    interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },
  },
}))

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

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

const renderModal = (props = {}) => {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
  return render(
    <QueryClientProvider client={qc}>
      <CreateHabitModal open={true} onClose={vi.fn()} {...props} />
    </QueryClientProvider>
  )
}

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

  it('does not render when open=false', () => {
    const qc = new QueryClient()
    render(
      <QueryClientProvider client={qc}>
        <CreateHabitModal open={false} onClose={vi.fn()} />
      </QueryClientProvider>
    )
    expect(screen.queryByText('Новая привычка')).not.toBeInTheDocument()
  })

  it('renders form when open=true', () => {
    renderModal()
    expect(screen.getByText('Новая привычка')).toBeInTheDocument()
    // Placeholder is "Например: Пить воду"
    expect(screen.getByPlaceholderText('Например: Пить воду')).toBeInTheDocument()
  })

  it('shows error when submitting empty name', async () => {
    renderModal()
    fireEvent.click(screen.getByText('Создать привычку'))
    await waitFor(() => {
      expect(screen.getByText('Введи название привычки')).toBeInTheDocument()
    })
  })

  it('submits habit successfully', async () => {
    habitsApi.create.mockResolvedValueOnce({ id: 1, name: 'Exercise' })
    const onClose = vi.fn()
    renderModal({ onClose })

    fireEvent.change(screen.getByPlaceholderText('Например: Пить воду'), {
      target: { value: 'Exercise' },
    })
    fireEvent.click(screen.getByText('Создать привычку'))

    await waitFor(() => {
      expect(habitsApi.create).toHaveBeenCalled()
    })
  })

  it('renders frequency options', () => {
    renderModal()
    expect(screen.getByText('Ежедневно')).toBeInTheDocument()
    // "По дням" is shown instead of "Еженедельно"
    expect(screen.getByText('По дням')).toBeInTheDocument()
  })

  it('calls onClose when close button clicked', () => {
    const onClose = vi.fn()
    renderModal({ onClose })
    const closeBtn = screen.getAllByRole('button')[0]
    fireEvent.click(closeBtn)
    expect(onClose).toHaveBeenCalled()
  })

  it('renders color options', () => {
    renderModal()
    // Colors rendered as buttons
    const buttons = screen.getAllByRole('button')
    expect(buttons.length).toBeGreaterThan(5)
  })
})
