import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
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 { PuntosDeVentaListPage } from '../../../features/puntos-de-venta/pages/PuntosDeVentaListPage'
import { useAuthStore } from '../../../stores/authStore'

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

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

const mockNavigate = vi.fn()
vi.mock('react-router-dom', async (importOriginal) => {
  const actual = await importOriginal<typeof import('react-router-dom')>()
  return { ...actual, useNavigate: () => mockNavigate }
})

const adminWithPdv = {
  id: 1,
  username: 'admin',
  nombre: 'Admin',
  rol: 'admin',
  permisos: ['administracion:puntos_de_venta:gestionar'],
  mustChangePassword: false,
}

const userWithoutPdv = {
  id: 2,
  username: 'cajero',
  nombre: 'Cajero',
  rol: 'cajero',
  permisos: [],
  mustChangePassword: false,
}

const mockMedios = [
  { id: 1, codigo: 'DIA01', nombre: 'Diario El Día', tipo: 1, plataformaEmpresaId: null, activo: true },
]

function makePdvs(n: number) {
  return Array.from({ length: n }, (_, i) => ({
    id: i + 1,
    medioId: 1,
    numeroAFIP: i + 1,
    nombre: `PdV ${i + 1}`,
    activo: true,
  }))
}

const server = setupServer()

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

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

describe('PuntosDeVentaListPage', () => {
  it('renders rows when API returns items', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/puntos-de-venta`, () =>
        HttpResponse.json({ items: makePdvs(3), page: 1, pageSize: 20, total: 3 }),
      ),
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: mockMedios, page: 1, pageSize: 200, total: 1 }),
      ),
    )

    renderPage()

    await waitFor(() => expect(screen.getByText('PdV 1')).toBeInTheDocument())
    expect(screen.getByText('PdV 2')).toBeInTheDocument()
    expect(screen.getByText('PdV 3')).toBeInTheDocument()
  })

  it('shows empty state when items is empty', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/puntos-de-venta`, () =>
        HttpResponse.json({ items: [], page: 1, pageSize: 20, total: 0 }),
      ),
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: mockMedios, page: 1, pageSize: 200, total: 1 }),
      ),
    )

    renderPage()

    await waitFor(() =>
      expect(screen.getByText(/sin resultados/i)).toBeInTheDocument(),
    )
  })

  it('hides "Nuevo punto de venta" button when user lacks permission', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/puntos-de-venta`, () =>
        HttpResponse.json({ items: [], page: 1, pageSize: 20, total: 0 }),
      ),
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: mockMedios, page: 1, pageSize: 200, total: 1 }),
      ),
    )

    renderPage(userWithoutPdv)

    await waitFor(() =>
      expect(screen.queryByRole('button', { name: /nuevo punto de venta/i })).not.toBeInTheDocument(),
    )
  })

  it('shows "Nuevo punto de venta" button when user has permission', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/puntos-de-venta`, () =>
        HttpResponse.json({ items: [], page: 1, pageSize: 20, total: 0 }),
      ),
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: mockMedios, page: 1, pageSize: 200, total: 1 }),
      ),
    )

    renderPage()

    await waitFor(() =>
      expect(screen.getByRole('button', { name: /nuevo punto de venta/i })).toBeInTheDocument(),
    )
  })

  it('prev button disabled on first page', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/puntos-de-venta`, () =>
        HttpResponse.json({ items: makePdvs(3), page: 1, pageSize: 20, total: 3 }),
      ),
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: mockMedios, page: 1, pageSize: 200, total: 1 }),
      ),
    )

    renderPage()

    await waitFor(() => expect(screen.getByText('PdV 1')).toBeInTheDocument())
    expect(screen.getByRole('button', { name: /anterior/i })).toBeDisabled()
  })
})
