import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { ErrorState } from '@/components/ui/ErrorState'
import { EmptyState } from '@/components/ui/EmptyState'
import { Badge } from '@/components/ui/Badge'
import { ApprovalStatus } from '@/components/orders/ApprovalStatus'
import type { AgentAction } from '@/lib/api/agent'

describe('ErrorState', () => {
  it('renders message and fires retry', () => {
    const onRetry = vi.fn()
    render(<ErrorState message="Boom" onRetry={onRetry} />)
    expect(screen.getByText('Boom')).toBeInTheDocument()
    fireEvent.click(screen.getByRole('button', { name: /try again/i }))
    expect(onRetry).toHaveBeenCalledTimes(1)
  })
})

describe('EmptyState', () => {
  it('renders title and description', () => {
    render(<EmptyState title="Nothing here" description="Create an order" />)
    expect(screen.getByText('Nothing here')).toBeInTheDocument()
    expect(screen.getByText('Create an order')).toBeInTheDocument()
  })
})

describe('Badge variants', () => {
  it.each(['success', 'danger', 'warning', 'info'] as const)('renders %s variant', variant => {
    render(<Badge variant={variant}>{variant}</Badge>)
    expect(screen.getByText(variant)).toBeInTheDocument()
  })
})

describe('ApprovalStatus', () => {
  const action = (over: Partial<AgentAction>): AgentAction =>
    ({
      id: 'a1',
      task_id: 't1',
      action_type: 'tool',
      tool_name: 'request_approval',
      description: '',
      input_data: {},
      output_data: {},
      status: 'completed',
      started_at: '2026-08-21T00:00:00Z',
      completed_at: null,
      error_message: null,
      ...over,
    }) as AgentAction

  it('shows empty state when no approval action exists', () => {
    render(<ApprovalStatus actions={[]} />)
    expect(screen.getByText(/no approvals/i)).toBeInTheDocument()
  })

  it('reflects pending status as warning', () => {
    render(<ApprovalStatus actions={[action({ output_data: { approval: { status: 'pending' } } })]} />)
    expect(screen.getByText(/purchase approval/i)).toBeInTheDocument()
    expect(screen.getAllByText('pending').length).toBeGreaterThan(0)
  })

  it('reflects approved status as success', () => {
    render(<ApprovalStatus actions={[action({ output_data: { approval: { status: 'approved' } } })]} />)
    expect(screen.getAllByText('approved').length).toBeGreaterThan(0)
  })
})