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

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/tasks', () => ({
  tasksApi: {
    create: vi.fn(),
    list: vi.fn(),
  },
}))

import { tasksApi } from '../api/tasks'

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

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

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

  it('renders form when open=true', () => {
    renderModal()
    expect(screen.getByText('Новая задача')).toBeInTheDocument()
    // Actual placeholder in component
    expect(screen.getByPlaceholderText('Что нужно сделать?')).toBeInTheDocument()
  })

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

  it('submits task successfully', async () => {
    tasksApi.create.mockResolvedValueOnce({ id: 1, title: 'Test Task' })
    const onClose = vi.fn()
    renderModal({ onClose })

    fireEvent.change(screen.getByPlaceholderText('Что нужно сделать?'), {
      target: { value: 'Test Task' },
    })
    fireEvent.click(screen.getByText('Создать задачу'))

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

  it('renders priority buttons', () => {
    renderModal()
    expect(screen.getByText('Без приоритета')).toBeInTheDocument()
    expect(screen.getByText('Низкий')).toBeInTheDocument()
    expect(screen.getByText('Средний')).toBeInTheDocument()
    expect(screen.getByText('Высокий')).toBeInTheDocument()
  })

  it('renders color picker', () => {
    renderModal()
    // Colors are rendered as buttons/divs
    const colorElements = document.querySelectorAll('[style*="background"]')
    expect(colorElements.length).toBeGreaterThan(0)
  })

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

  it('renders recurring toggle', () => {
    renderModal()
    // The label says "Повторять" in the component
    expect(screen.getByText('Повторять')).toBeInTheDocument()
  })
})
