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

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: {
    update: vi.fn(),
    delete: vi.fn(),
  },
}))

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

const mockTask = {
  id: 1,
  title: 'Test Task',
  description: 'Description',
  color: '#6366f1',
  icon: '📋',
  due_date: '2026-03-26',
  priority: 1,
  reminder_time: null,
  is_recurring: false,
  recurrence_type: null,
  recurrence_interval: 1,
  recurrence_end_date: null,
}

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

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

  it('does not render when open=false', () => {
    const qc = new QueryClient()
    render(
      <QueryClientProvider client={qc}>
        <EditTaskModal open={false} onClose={vi.fn()} task={mockTask} />
      </QueryClientProvider>
    )
    expect(screen.queryByText('Редактировать задачу')).not.toBeInTheDocument()
  })

  it('renders with task data pre-filled', () => {
    renderModal()
    const titleInput = screen.getByDisplayValue('Test Task')
    expect(titleInput).toBeInTheDocument()
  })

  it('renders edit modal title', () => {
    renderModal()
    expect(screen.getByText('Редактировать задачу')).toBeInTheDocument()
  })

  it('submits updated task', async () => {
    tasksApi.update.mockResolvedValueOnce({ id: 1, title: 'Updated' })
    renderModal()

    const titleInput = screen.getByDisplayValue('Test Task')
    fireEvent.change(titleInput, { target: { value: 'Updated Task' } })
    fireEvent.click(screen.getByText('Сохранить'))

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

  it('shows delete confirmation button', () => {
    renderModal()
    // Button says "Удалить задачу"
    expect(screen.getByText('Удалить задачу')).toBeInTheDocument()
  })

  it('shows delete confirmation when delete clicked', () => {
    renderModal()
    fireEvent.click(screen.getByText('Удалить задачу'))
    // Confirmation shows "Да, удалить"
    expect(screen.getByText('Да, удалить')).toBeInTheDocument()
  })

  it('deletes task after confirmation', async () => {
    tasksApi.delete.mockResolvedValueOnce({})
    renderModal()
    fireEvent.click(screen.getByText('Удалить задачу'))
    fireEvent.click(screen.getByText('Да, удалить'))

    await waitFor(() => {
      expect(tasksApi.delete).toHaveBeenCalledWith(1)
    })
  })
})
