import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { WorkflowActions } from '@/components/orders/WorkflowActions'
import type { AgentAction, Order } from '@/lib/api/agent'

vi.mock('@/components/ui/Toast', () => ({
  useToast: () => ({ toast: vi.fn() }),
}))

vi.mock('@/components/providers/BusinessProvider', () => ({
  useBusiness: () => ({
    business: { businessId: '11111111-1111-1111-1111-111111111111' },
    refresh: vi.fn(),
  }),
}))

function makeOrder(status: string): Order {
  return {
    id: 'order-1',
    business_id: 'b-1',
    customer_id: 'c-1',
    status,
    priority: 'normal',
    total_amount: 100,
    delivery_address: 'Kigali',
    created_at: '2026-08-21T00:00:00Z',
    updated_at: '2026-08-21T00:00:00Z',
    customer: { id: 'c-1', name: 'Jean', email: 'j@x.rw', phone: '+250' },
    items: [],
  }
}

const noActions: AgentAction[] = []
const noop = async () => {}

function renderActions(order: Order, actions: AgentAction[] = noActions, purchaseRequestId: string | null = null) {
  const trigger = vi.fn().mockResolvedValue(undefined)
  const action = vi.fn().mockResolvedValue(undefined)
  render(
    <WorkflowActions
      order={order}
      actions={actions}
      purchaseRequestId={purchaseRequestId}
      triggering={false}
      actionLoading={null}
      handleTriggerOrderCreated={trigger}
      handleAction={action}
    />
  )
  return { trigger, action }
}

describe('WorkflowActions status matrix', () => {
  it('pending shows trigger analysis button', () => {
    const { trigger } = renderActions(makeOrder('pending'))
    const btn = screen.getByRole('button', { name: /trigger imbaraga analysis/i })
    fireEvent.click(btn)
    expect(trigger).toHaveBeenCalledTimes(1)
  })

  it('awaiting_approval links to approval center', () => {
    renderActions(makeOrder('awaiting_approval'))
    expect(screen.getByText(/approval required/i)).toBeInTheDocument()
    expect(screen.getByText(/view approvals/i)).toBeInTheDocument()
  })

  it('supplier_pending without PR id shows waiting message, no action button', () => {
    renderActions(makeOrder('supplier_pending'))
    expect(screen.getByText(/creating purchase request/i)).toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /submit purchase request/i })).not.toBeInTheDocument()
  })

  it('supplier_pending with unsubmitted PR shows Submit button passing PR id', () => {
    const { action } = renderActions(makeOrder('supplier_pending'), noActions, 'pr-123')
    const btn = screen.getByRole('button', { name: /submit purchase request/i })
    fireEvent.click(btn)
    expect(action).toHaveBeenCalledWith('submit', 'pr-123')
  })

  it('supplier_pending with submitted PR shows Fulfill button', () => {
    const actions = [
      { id: 'a1', task_id: 't1', action_type: 'tool', tool_name: 'submit_purchase_request', description: '', input_data: {}, output_data: {}, status: 'completed', started_at: '2026-08-21T00:00:00Z', completed_at: null, error_message: null },
    ] as unknown as AgentAction[]
    const { action } = renderActions(makeOrder('supplier_pending'), actions, 'pr-123')
    const btn = screen.getByRole('button', { name: /fulfill purchase/i })
    fireEvent.click(btn)
    expect(action).toHaveBeenCalledWith('fulfill', 'pr-123')
  })

  it('ready shows Deliver button (fulfillment already done)', () => {
    const { action } = renderActions(makeOrder('ready'))
    const btn = screen.getByRole('button', { name: /deliver order/i })
    fireEvent.click(btn)
    expect(action).toHaveBeenCalledWith('deliver')
  })

  it('completed shows completion card with no buttons', () => {
    renderActions(makeOrder('completed'))
    expect(screen.getByText(/order completed/i)).toBeInTheDocument()
    expect(screen.queryByRole('button')).not.toBeInTheDocument()
  })
})