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 { ProductsPage } from '../../../features/products/pages/ProductsPage'
import { useAuthStore } from '../../../stores/authStore'
import type { ProductListItem, PagedResult } from '../../../features/products/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:productos:gestionar'],
  mustChangePassword: false,
}

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

const mockItem: ProductListItem = {
  id: 1,
  nombre: 'Clasificado Estándar',
  medioId: 1,
  productTypeId: 2,
  rubroId: null,
  basePrice: 100.50,
  priceDurationDays: null,
  isActive: true,
}

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

const emptyPaged: PagedResult<ProductListItem> = {
  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/products']}>
        <Routes>
          <Route path="/admin/products" element={<ProductsPage />} />
        </Routes>
      </MemoryRouter>
    </QueryClientProvider>,
  )
}

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

describe('ProductsPage — loading and error states', () => {
  it('renders loading skeleton while fetching', () => {
    server.use(
      http.get(`${API_URL}/api/v1/products`, async () => {
        await new Promise(() => {})
        return HttpResponse.json(emptyPaged)
      }),
    )
    renderPage()
    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/products`, () => HttpResponse.json(mockPaged)),
    )
    renderPage()
    await waitFor(() => expect(screen.getByText('Clasificado Estándar')).toBeInTheDocument())
  })

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

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

// ─── Permission gating ───────────────────────────────────────────────────────

describe('ProductsPage — permission gating', () => {
  it('shows "Nuevo Producto" button when user has permission', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/products`, () => HttpResponse.json(emptyPaged)),
    )
    renderPage(adminUser)
    await waitFor(() =>
      expect(screen.getByRole('button', { name: /nuevo producto/i })).toBeInTheDocument(),
    )
  })

  it('hides "Nuevo Producto" button when user lacks permission', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/products`, () => HttpResponse.json(mockPaged)),
    )
    renderPage(regularUser)
    await waitFor(() => expect(screen.getByText('Clasificado Estándar')).toBeInTheDocument())
    expect(screen.queryByRole('button', { name: /nuevo producto/i })).not.toBeInTheDocument()
  })
})

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

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

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

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