import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fetchAdminOrders } from '@/entities/order/api/admin-order-api'
import type { AdminOrderListItem } from '@/entities/order/api/admin-order-api'
import { AdminOrdersPage } from '../AdminOrdersPage'

vi.mock('@/entities/order/api/admin-order-api', () => ({
  fetchAdminOrders: vi.fn(),
  fetchAdminOrder: vi.fn(),
}))

const fetchAdminOrdersMock = vi.mocked(fetchAdminOrders)

function renderPage() {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
      },
    },
  })

  return render(
    <QueryClientProvider client={queryClient}>
      <AdminOrdersPage />
    </QueryClientProvider>,
  )
}

type AdminOrderListItemWithApproval = AdminOrderListItem & { deliveryFeeLocked?: boolean }

function createOrder(overrides?: Partial<AdminOrderListItemWithApproval>): AdminOrderListItemWithApproval {
  return {
    id: 'order-12345678',
    status: 'PENDING_PAYMENT',
    deliveryType: 'delivery' as const,
    deliveryCarrier: null,
    paymentMethod: 'online' as const,
    totalCents: 10000,
    currency: 'RUB',
    createdAt: '2026-05-28T10:00:00.000Z',
    updatedAt: '2026-05-28T10:00:00.000Z',
    user: { id: 'user-1', email: 'buyer@example.com' },
    itemsCount: 1,
    ...overrides,
  }
}

function mockOrdersResponse(order: AdminOrderListItemWithApproval) {
  fetchAdminOrdersMock.mockResolvedValueOnce({
    items: [order],
    total: 1,
    page: 1,
    pageSize: 20,
  })
}

describe('AdminOrdersPage', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('показывает бейдж для PENDING_PAYMENT + delivery + deliveryFeeLocked=false', async () => {
    mockOrdersResponse(createOrder({ deliveryFeeLocked: false }))

    renderPage()

    expect(await screen.findByText('Цена не подтверждена')).toBeInTheDocument()
    expect(screen.getByText('12345678')).toBeInTheDocument()
  })

  it('не показывает бейдж для PENDING_PAYMENT + pickup + deliveryFeeLocked=false', async () => {
    mockOrdersResponse(
      createOrder({
        id: 'order-87654321',
        deliveryType: 'pickup',
        deliveryFeeLocked: false,
      }),
    )

    renderPage()

    expect(await screen.findByText('87654321')).toBeInTheDocument()
    expect(screen.queryByText('Цена не подтверждена')).not.toBeInTheDocument()
  })

  it('не показывает бейдж для PAID + delivery + deliveryFeeLocked=false', async () => {
    mockOrdersResponse(
      createOrder({
        id: 'order-45671234',
        status: 'PAID',
        deliveryFeeLocked: false,
      }),
    )

    renderPage()

    expect(await screen.findByText('45671234')).toBeInTheDocument()
    expect(screen.queryByText('Цена не подтверждена')).not.toBeInTheDocument()
  })

  it('не показывает бейдж при отсутствии deliveryFeeLocked', async () => {
    mockOrdersResponse(
      createOrder({
        id: 'order-11223344',
        deliveryFeeLocked: undefined,
      }),
    )

    renderPage()

    expect(await screen.findByText('11223344')).toBeInTheDocument()
    expect(screen.queryByText('Цена не подтверждена')).not.toBeInTheDocument()
  })

  it('вызывает fetchAdminOrders на стартовом рендере', async () => {
    mockOrdersResponse(createOrder({ id: 'order-99887766', deliveryFeeLocked: true }))

    renderPage()

    await screen.findByText('99887766')
    expect(fetchAdminOrdersMock).toHaveBeenCalledTimes(1)
  })
})
