import type { ReactNode } from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import type { WebhookDelivery } from '@/types/webhook'
import { DeliveryDetailModal } from './DeliveryDetailModal'

vi.mock('antd', () => {
  const Descriptions = ({
    children,
  }: {
    children?: ReactNode
  }) => <div>{children}</div>

  return {
    Alert: ({
      message,
      description,
    }: {
      message?: ReactNode
      description?: ReactNode
    }) => (
      <div>
        <div>{message}</div>
        <div>{description}</div>
      </div>
    ),
    Descriptions: Object.assign(Descriptions, {
      Item: ({
        label,
        children,
      }: {
        label?: ReactNode
        children?: ReactNode
      }) => (
        <div>
          <span>{label}</span>
          <span>{children}</span>
        </div>
      ),
    }),
    Modal: ({
      open,
      title,
      onCancel,
      children,
    }: {
      open: boolean
      title?: ReactNode
      onCancel?: () => void
      children?: ReactNode
    }) => (
      open ? (
        <div data-testid="delivery-detail-modal-root">
          <h1>{title}</h1>
          {children}
          <button type="button" onClick={onCancel}>modal close</button>
        </div>
      ) : null
    ),
    Typography: {
      Paragraph: ({
        children,
      }: {
        children?: ReactNode
      }) => <pre>{children}</pre>,
      Text: ({
        children,
      }: {
        children?: ReactNode
      }) => <span>{children}</span>,
    },
  }
})

function buildDelivery(overrides?: Partial<WebhookDelivery>): WebhookDelivery {
  return {
    id: 5,
    webhook_id: 9,
    event_type: 'user.registered',
    payload: '{"user":"alice"}',
    status_code: 204,
    response_body: '{"ok":true}',
    attempt: 1,
    success: true,
    error: '',
    delivered_at: '2026-03-28 09:30:00',
    created_at: '2026-03-28 09:29:00',
    ...overrides,
  }
}

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

  afterEach(() => {
    vi.restoreAllMocks()
  })

  it('returns null when there is no delivery', () => {
    const { container } = render(
      <DeliveryDetailModal
        open
        delivery={null}
        onClose={vi.fn()}
      />,
    )

    expect(container).toBeEmptyDOMElement()
  })

  it('renders formatted payload and response content for successful deliveries', async () => {
    const user = userEvent.setup()
    const onClose = vi.fn()

    render(
      <DeliveryDetailModal
        open
        delivery={buildDelivery()}
        onClose={onClose}
      />,
    )

    expect(screen.getByTestId('delivery-detail-modal-root')).toBeInTheDocument()
    expect(screen.getByText('user.registered')).toBeInTheDocument()
    expect(screen.getByText('204')).toBeInTheDocument()
    expect(screen.getByText('成功')).toBeInTheDocument()
    expect(screen.getByText(/"user": "alice"/)).toBeInTheDocument()
    expect(screen.getByText(/"ok": true/)).toBeInTheDocument()
    expect(screen.queryByText('错误信息')).not.toBeInTheDocument()

    await user.click(screen.getByRole('button', { name: 'modal close' }))
    expect(onClose).toHaveBeenCalledTimes(1)
  })

  it('renders failure placeholders, alerts, and raw payload text', () => {
    render(
      <DeliveryDetailModal
        open
        delivery={buildDelivery({
          payload: 'not-json',
          response_body: '',
          status_code: 0,
          success: false,
          error: 'delivery failed',
          delivered_at: '',
        })}
        onClose={vi.fn()}
      />,
    )

    expect(screen.getByText('失败')).toBeInTheDocument()
    expect(screen.getByText('delivery failed')).toBeInTheDocument()
    expect(screen.getByText('错误信息')).toBeInTheDocument()
    expect(screen.getByText('not-json')).toBeInTheDocument()
    expect(screen.getAllByText('-').length).toBeGreaterThan(0)
  })
})
