import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter } from 'react-router-dom'
import { DeactivateSeccionModal } from '../../../features/secciones/components/DeactivateSeccionModal'

const API_URL = 'http://localhost:5000'

vi.mock('sonner', () => ({
  toast: { success: vi.fn(), error: vi.fn() },
}))

const server = setupServer()

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
afterEach(() => {
  server.resetHandlers()
  vi.clearAllMocks()
})
afterAll(() => server.close())

function renderModal(activo = true) {
  const qc = new QueryClient({
    defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  })
  return render(
    <QueryClientProvider client={qc}>
      <MemoryRouter>
        <DeactivateSeccionModal seccionId={1} seccionNombre="Clasificados Autos" activo={activo} />
      </MemoryRouter>
    </QueryClientProvider>,
  )
}

describe('DeactivateSeccionModal', () => {
  it('shows "Desactivar" trigger when sección is active', () => {
    renderModal(true)
    expect(screen.getByRole('button', { name: /desactivar/i })).toBeInTheDocument()
  })

  it('shows "Reactivar" trigger when sección is inactive', () => {
    renderModal(false)
    expect(screen.getByRole('button', { name: /reactivar/i })).toBeInTheDocument()
  })

  it('opens dialog and shows confirmation text', async () => {
    renderModal(true)
    await userEvent.click(screen.getByRole('button', { name: /desactivar/i }))
    await waitFor(() =>
      expect(screen.getByText(/desactivar sección/i)).toBeInTheDocument(),
    )
    expect(screen.getByText(/clasificados autos/i)).toBeInTheDocument()
  })

  it('calls deactivate endpoint on confirm', async () => {
    let called = false
    server.use(
      http.post(`${API_URL}/api/v1/admin/secciones/1/deactivate`, () => {
        called = true
        return new HttpResponse(null, { status: 204 })
      }),
    )

    renderModal(true)
    await userEvent.click(screen.getByRole('button', { name: /desactivar/i }))
    await waitFor(() => screen.getByRole('alertdialog'))
    await userEvent.click(screen.getByRole('button', { name: /desactivar$/i }))

    await waitFor(() => expect(called).toBe(true))
  })
})
