import { describe, it, expect, vi, beforeAll, afterAll, afterEach } 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 React from 'react'
import { ProductTypeFormDialog } from '../../../features/product-types/components/ProductTypeFormDialog'
import type { ProductTypeDetail } from '../../../features/product-types/types'

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

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

const mockDetail: ProductTypeDetail = {
  id: 1,
  nombre: 'Clasificados',
  hasDuration: true,
  requiresText: true,
  requiresCategory: false,
  isBundle: false,
  allowImages: false,
  maxImages: null,
  maxImageSizeMB: null,
  maxImageWidth: null,
  maxImageHeight: null,
  isActive: true,
  fechaCreacion: '2026-04-19T00:00:00Z',
  fechaModificacion: null,
}

const server = setupServer()

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

function wrap(children: React.ReactNode) {
  const qc = new QueryClient({
    defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  })
  return render(
    <QueryClientProvider client={qc}>
      <MemoryRouter>{children}</MemoryRouter>
    </QueryClientProvider>,
  )
}

// ─── ProductTypeFormDialog — create mode ──────────────────────────────────

describe('ProductTypeFormDialog — create mode', () => {
  it('renders create dialog title when no productType prop', () => {
    wrap(
      <ProductTypeFormDialog open={true} onOpenChange={vi.fn()} />,
    )
    expect(screen.getByRole('heading', { name: /nuevo tipo/i })).toBeInTheDocument()
  })

  it('has aria-describedby on DialogDescription (NFR8)', () => {
    wrap(
      <ProductTypeFormDialog open={true} onOpenChange={vi.fn()} />,
    )
    const desc = screen.getByText(/completá los datos/i)
    expect(desc).toBeInTheDocument()
  })

  it('calls create mutation and closes dialog on success', async () => {
    server.use(
      http.post(`${API_URL}/api/v1/admin/product-types`, () =>
        HttpResponse.json({ id: 5, nombre: 'Nuevo Tipo' }, { status: 201 }),
      ),
    )
    const onOpenChange = vi.fn()
    wrap(
      <ProductTypeFormDialog open={true} onOpenChange={onOpenChange} />,
    )
    await userEvent.type(screen.getByLabelText(/nombre/i), 'Nuevo Tipo')
    await userEvent.click(screen.getByRole('button', { name: /guardar|crear/i }))
    await waitFor(() => {
      expect(onOpenChange).toHaveBeenCalledWith(false)
    })
  })

  it('shows inline error when backend returns 409 NombreDuplicado', async () => {
    server.use(
      http.post(`${API_URL}/api/v1/admin/product-types`, () =>
        HttpResponse.json(
          { error: 'producto_tipo_nombre_duplicado', message: 'Ya existe un tipo con ese nombre' },
          { status: 409 },
        ),
      ),
    )
    wrap(
      <ProductTypeFormDialog open={true} onOpenChange={vi.fn()} />,
    )
    await userEvent.type(screen.getByLabelText(/nombre/i), 'Duplicado')
    await userEvent.click(screen.getByRole('button', { name: /guardar|crear/i }))
    await waitFor(() => {
      expect(screen.getByText(/ya existe un tipo con ese nombre/i)).toBeInTheDocument()
    })
  })
})

// ─── ProductTypeFormDialog — edit mode ────────────────────────────────────

describe('ProductTypeFormDialog — edit mode', () => {
  it('renders edit dialog title and pre-fills nombre', () => {
    wrap(
      <ProductTypeFormDialog open={true} onOpenChange={vi.fn()} productType={mockDetail} />,
    )
    expect(screen.getByRole('heading', { name: /editar tipo/i })).toBeInTheDocument()
    const input = screen.getByLabelText(/nombre/i) as HTMLInputElement
    expect(input.value).toBe('Clasificados')
  })

  it('calls update mutation and closes dialog on success', async () => {
    server.use(
      http.put(`${API_URL}/api/v1/admin/product-types/1`, () =>
        HttpResponse.json({ ...mockDetail, nombre: 'Modificado' }),
      ),
    )
    const onOpenChange = vi.fn()
    wrap(
      <ProductTypeFormDialog open={true} onOpenChange={onOpenChange} productType={mockDetail} />,
    )
    const input = screen.getByLabelText(/nombre/i) as HTMLInputElement
    await userEvent.clear(input)
    await userEvent.type(input, 'Modificado')
    await userEvent.click(screen.getByRole('button', { name: /guardar/i }))
    await waitFor(() => {
      expect(onOpenChange).toHaveBeenCalledWith(false)
    })
  })
})
