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, Routes, Route } from 'react-router-dom'
import React from 'react'
import { ProductTypesPage } from '../../../features/product-types/pages/ProductTypesPage'
import { useAuthStore } from '../../../stores/authStore'
import type { ProductTypeListItem, PagedResult } from '../../../features/product-types/types'

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

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

const adminUser = {
  id: 1,
  username: 'admin',
  nombre: 'Admin',
  rol: 'admin',
  permisos: ['catalogo:tipos:gestionar'],
  mustChangePassword: false,
}

const regularUser = {
  id: 2,
  username: 'viewer',
  nombre: 'Viewer',
  rol: 'viewer',
  permisos: [],
  mustChangePassword: false,
}

const mockItem: ProductTypeListItem = {
  id: 1,
  nombre: 'Clasificados',
  hasDuration: true,
  requiresText: true,
  requiresCategory: false,
  isBundle: false,
  allowImages: false,
  isActive: true,
}

const mockPaged: PagedResult<ProductTypeListItem> = {
  items: [mockItem],
  page: 1,
  pageSize: 20,
  total: 1,
}

const emptyPaged: PagedResult<ProductTypeListItem> = {
  items: [],
  page: 1,
  pageSize: 20,
  total: 0,
}

const server = setupServer()

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

function renderPage(user = adminUser) {
  useAuthStore.setState({ user })
  const qc = new QueryClient({
    defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
  })
  return render(
    <QueryClientProvider client={qc}>
      <MemoryRouter initialEntries={['/admin/product-types']}>
        <Routes>
          <Route path="/admin/product-types" element={<ProductTypesPage />} />
        </Routes>
      </MemoryRouter>
    </QueryClientProvider>,
  )
}

// ─── Loading / Error / Data states ──────────────────────────────────────────

describe('ProductTypesPage — loading and error states', () => {
  it('renders loading skeleton while fetching', () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, async () => {
        await new Promise(() => {})
        return HttpResponse.json(emptyPaged)
      }),
    )
    renderPage()
    // During loading, skeletons are shown — verify they are rendered
    const skeletons = document.querySelectorAll('[class*="skeleton"], .animate-pulse')
    expect(skeletons.length).toBeGreaterThan(0)
  })

  it('renders data when loaded', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () => HttpResponse.json(mockPaged)),
    )
    renderPage()
    await waitFor(() => expect(screen.getByText('Clasificados')).toBeInTheDocument())
  })

  it('shows error state on fetch failure', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () =>
        HttpResponse.json({ error: 'server_error' }, { status: 500 }),
      ),
    )
    renderPage()
    await waitFor(() =>
      expect(screen.getByText(/error al cargar tipos de producto/i)).toBeInTheDocument(),
    )
  })

  it('shows empty state when no product types', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () => HttpResponse.json(emptyPaged)),
    )
    renderPage()
    await waitFor(() =>
      expect(screen.getByText(/no hay tipos de producto/i)).toBeInTheDocument(),
    )
  })
})

// ─── Create dialog ───────────────────────────────────────────────────────────

describe('ProductTypesPage — create dialog', () => {
  it('opens create dialog when "Nuevo Tipo" button is clicked', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () => HttpResponse.json(mockPaged)),
    )
    renderPage(adminUser)
    await waitFor(() => expect(screen.getByRole('button', { name: /nuevo tipo/i })).toBeInTheDocument())
    await userEvent.click(screen.getByRole('button', { name: /nuevo tipo/i }))
    await waitFor(() =>
      expect(screen.getByRole('heading', { name: /nuevo tipo de producto/i })).toBeInTheDocument(),
    )
  })

  it('opens create dialog from empty state CTA', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () => HttpResponse.json(emptyPaged)),
    )
    renderPage(adminUser)
    await waitFor(() => expect(screen.getByRole('button', { name: /crear primer tipo/i })).toBeInTheDocument())
    await userEvent.click(screen.getByRole('button', { name: /crear primer tipo/i }))
    await waitFor(() =>
      expect(screen.getByRole('heading', { name: /nuevo tipo de producto/i })).toBeInTheDocument(),
    )
  })

  it('hides "Nuevo Tipo" button when user lacks permission', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () => HttpResponse.json(mockPaged)),
    )
    renderPage(regularUser)
    await waitFor(() => expect(screen.getByText('Clasificados')).toBeInTheDocument())
    expect(screen.queryByRole('button', { name: /nuevo tipo/i })).not.toBeInTheDocument()
  })
})

// ─── Edit dialog ─────────────────────────────────────────────────────────────

describe('ProductTypesPage — edit dialog', () => {
  it('opens edit dialog pre-filled when Edit button is clicked', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () => HttpResponse.json(mockPaged)),
    )
    renderPage(adminUser)
    await waitFor(() => expect(screen.getByText('Clasificados')).toBeInTheDocument())
    await userEvent.click(screen.getByRole('button', { name: /editar/i }))
    await waitFor(() =>
      expect(screen.getByRole('heading', { name: /editar tipo/i })).toBeInTheDocument(),
    )
    const input = screen.getByLabelText(/nombre/i) as HTMLInputElement
    expect(input.value).toBe('Clasificados')
  })
})

// ─── Deactivate dialog ───────────────────────────────────────────────────────

describe('ProductTypesPage — deactivate dialog', () => {
  it('opens deactivate confirmation dialog when Desactivar is clicked', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/product-types`, () => HttpResponse.json(mockPaged)),
    )
    renderPage(adminUser)
    await waitFor(() => expect(screen.getByText('Clasificados')).toBeInTheDocument())
    await userEvent.click(screen.getByRole('button', { name: /desactivar/i }))
    await waitFor(() =>
      expect(screen.getByRole('heading', { name: /desactivar tipo de producto/i })).toBeInTheDocument(),
    )
  })
})
