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 { MediosListPage } from '../../../features/medios/pages/MediosListPage'
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 adminUserWithMedios = {
  id: 1,
  username: 'admin',
  nombre: 'Admin',
  rol: 'admin',
  permisos: ['administracion:medios:gestionar'],
  mustChangePassword: false,
}

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

function makeMedios(n: number) {
  return Array.from({ length: n }, (_, i) => ({
    id: i + 1,
    codigo: `MEDIO${i + 1}`,
    nombre: `Medio ${i + 1}`,
    tipo: (i % 4) + 1,
    plataformaEmpresaId: null,
    activo: true,
  }))
}

const server = setupServer()

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

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

describe('MediosListPage', () => {
  it('renders seed rows when API returns items', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: makeMedios(3), page: 1, pageSize: 20, total: 3 }),
      ),
    )

    renderPage()

    await waitFor(() => expect(screen.getByText('MEDIO1')).toBeInTheDocument())
    expect(screen.getByText('MEDIO2')).toBeInTheDocument()
    expect(screen.getByText('MEDIO3')).toBeInTheDocument()
  })

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

    renderPage()

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

  it('hides "Nuevo medio" button when user lacks permission', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: makeMedios(2), page: 1, pageSize: 20, total: 2 }),
      ),
    )

    renderPage(adminUserWithoutMedios)

    // Wait for page to render
    await waitFor(() => expect(screen.queryByRole('button', { name: /nuevo medio/i })).not.toBeInTheDocument())
  })

  it('shows "Nuevo medio" button when user has permission', async () => {
    server.use(
      http.get(`${API_URL}/api/v1/admin/medios`, () =>
        HttpResponse.json({ items: makeMedios(2), page: 1, pageSize: 20, total: 2 }),
      ),
    )

    renderPage()

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

  it('filter by tipo adds querystring tipo', async () => {
    const requests: string[] = []
    server.use(
      http.get(`${API_URL}/api/v1/admin/medios`, ({ request }) => {
        requests.push(request.url)
        return HttpResponse.json({ items: [], page: 1, pageSize: 20, total: 0 })
      }),
    )

    renderPage()

    await waitFor(() => expect(requests.length).toBeGreaterThan(0))

    // Open the Radix Select trigger and pick "Diario" (value=1)
    await userEvent.click(screen.getByRole('combobox', { name: /tipo/i }))
    await userEvent.click(screen.getByRole('option', { name: /^diario$/i }))

    await waitFor(() => {
      const filtered = requests.find((u) => u.includes('tipo=1'))
      expect(filtered).toBeTruthy()
    })
  })

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

    renderPage()

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