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

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: {
    update: vi.fn(),
    delete: vi.fn(),
    getFreezes: vi.fn().mockResolvedValue([]),
    addFreeze: vi.fn(),
    deleteFreeze: vi.fn(),
  },
}))

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

const mockHabit = {
  id: 1,
  name: 'Exercise',
  description: 'Daily workout',
  color: '#6366f1',
  icon: '💪',
  frequency: 'daily',
  target_days: [],
  target_count: 1,
  reminder_time: null,
  start_date: '2026-01-01',
}

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

describe('EditHabitModal', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    habitsApi.getFreezes.mockResolvedValue([])
  })

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

  it('renders with habit data', () => {
    renderModal()
    expect(screen.getByText('Редактировать привычку')).toBeInTheDocument()
    expect(screen.getByDisplayValue('Exercise')).toBeInTheDocument()
  })

  it('renders save button', () => {
    renderModal()
    // Button text is "Сохранить изменения"
    expect(screen.getByText('Сохранить изменения')).toBeInTheDocument()
  })

  it('submits updated habit', async () => {
    habitsApi.update.mockResolvedValueOnce({ id: 1, name: 'Updated' })
    renderModal()

    fireEvent.change(screen.getByDisplayValue('Exercise'), {
      target: { value: 'Updated Exercise' },
    })
    fireEvent.click(screen.getByText('Сохранить изменения'))

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

  it('renders delete button', () => {
    renderModal()
    // Button text is "Удалить привычку"
    expect(screen.getByText('Удалить привычку')).toBeInTheDocument()
  })

  it('shows delete confirmation when delete clicked', () => {
    renderModal()
    fireEvent.click(screen.getByText('Удалить привычку'))
    // Confirmation shows "Удалить привычку?" and confirm button "Удалить"
    expect(screen.getByText('Удалить привычку?')).toBeInTheDocument()
  })

  it('deletes habit on confirmation', async () => {
    habitsApi.delete.mockResolvedValueOnce({})
    renderModal()
    fireEvent.click(screen.getByText('Удалить привычку'))
    // Confirm button shows "Удалить"
    const deleteBtn = screen.getAllByText('Удалить').find(el => el.tagName === 'BUTTON')
    fireEvent.click(deleteBtn)

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

  it('renders freezes section', async () => {
    renderModal()
    await waitFor(() => {
      expect(screen.getByText(/Заморозки/)).toBeInTheDocument()
    })
  })
})
