import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'

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

const statusFixture = {
  agents_enabled: true,
  agents_pause_reason: '',
  blocked_tools: [] as string[],
  available_tools: ['check_inventory', 'send_customer_notification', 'update_agent_task'],
  master_prompt: { prompt_key: 'master', instruction: 'operate safely', version: 3, updated_by: null, updated_at: null },
  paused_businesses: [{ id: 'b-1', name: 'Kigali Smart Supplies' }],
  recent_control: [
    { action: 'agents.disabled', target: null, detail: { reason: 'demo freeze' }, actor_user_id: null, created_at: '2026-08-29T10:00:00Z' },
  ],
}

const feedFixture = {
  tasks: [
    {
      id: 't-1', business_id: 'b-1', business_name: 'Kigali Smart Supplies',
      task_type: 'order_fulfillment', status: 'running', objective: null, order_id: null,
      scheduled_for: null, started_at: '2026-08-29T10:00:00Z', completed_at: null,
    },
    {
      id: 't-2', business_id: 'b-1', business_name: 'Kigali Smart Supplies',
      task_type: 'inventory_restock', status: 'completed', objective: null, order_id: null,
      scheduled_for: null, started_at: '2026-08-29T09:00:00Z', completed_at: null,
    },
  ],
  executions: [],
  actions: [],
}

const approvalsFixture = [
  {
    id: 'ap-1', business_id: 'b-1', business_name: 'Kigali Smart Supplies',
    task_id: 't-1', action_type: 'purchase_request', title: 'Restock monitors',
    description: 'Procure 5 monitors', amount: 2500.5, status: 'pending',
    requested_at: '2026-08-29T10:00:00Z', resolved_at: null, resolved_by: null,
  },
]

const api = vi.hoisted(() => ({
  cancelAgentTask: vi.fn(),
  getAgentFeed: vi.fn(),
  getPlatformApprovals: vi.fn(),
  getSystemStatus: vi.fn(),
  setBlockedTools: vi.fn(),
  setBusinessAgents: vi.fn(),
  setGlobalAgents: vi.fn(),
}))

vi.mock('@/lib/api/platform', () => api)

describe('Agent Control page', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    api.getSystemStatus.mockResolvedValue({ success: true as const, data: statusFixture })
    api.getAgentFeed.mockResolvedValue({ success: true as const, data: feedFixture })
    api.getPlatformApprovals.mockResolvedValue({ success: true as const, data: { see_only: true, approvals: approvalsFixture } })
    api.setGlobalAgents.mockResolvedValue({ success: true as const, data: { enabled: false, reason: '' } })
    api.cancelAgentTask.mockResolvedValue({ success: true as const, data: { status: 'cancelled' } })
  })

  it('shows the kill-switch, feed and cross-tenant approvals', async () => {
    const { default: AgentControlPage } = await import('@/app/platform/control/page')
    render(<AgentControlPage />)
    expect(await screen.findByText('Agent Control')).toBeInTheDocument()
    expect(screen.getByText('Global agents')).toBeInTheDocument()
    expect(screen.getByText('Running')).toBeInTheDocument()
    expect(screen.getByText('Cross-tenant approvals')).toBeInTheDocument()
    expect(await screen.findAllByText('Kigali Smart Supplies')).not.toHaveLength(0)
  })

  it('pauses all agents on demand', async () => {
    const { default: AgentControlPage } = await import('@/app/platform/control/page')
    render(<AgentControlPage />)
    fireEvent.click(await screen.findByRole('button', { name: /pause all agents/i }))
    await waitFor(() => expect(api.setGlobalAgents).toHaveBeenCalledWith(false, ''))
  })

  it('only shows Cancel for non-terminal tasks', async () => {
    const { default: AgentControlPage } = await import('@/app/platform/control/page')
    render(<AgentControlPage />)
    const cancelButtons = await screen.findAllByRole('button', { name: /cancel/i })
    expect(cancelButtons.length).toBe(1)
    fireEvent.click(cancelButtons[0])
    await waitFor(() => expect(api.cancelAgentTask).toHaveBeenCalledWith('t-1'))
  })

  it('blocks and unblocks a tool', async () => {
    const { default: AgentControlPage } = await import('@/app/platform/control/page')
    api.setBlockedTools.mockResolvedValue({ success: true as const, data: { blocked_tools: ['send_customer_notification'] } })
    render(<AgentControlPage />)
    const sendNotif = await screen.findByRole('checkbox', { name: /send_customer_notification/i })
    fireEvent.click(sendNotif)
    fireEvent.click(screen.getByRole('button', { name: /save blocked tools/i }))
    await waitFor(() => expect(api.setBlockedTools).toHaveBeenCalledWith(['send_customer_notification']))
  })

  it('renders an error state when status load fails', async () => {
    const { default: AgentControlPage } = await import('@/app/platform/control/page')
    api.getSystemStatus.mockResolvedValue({ success: false as const, error_code: 'HTTP_ERROR', message: 'boom' })
    render(<AgentControlPage />)
    expect(await screen.findByText('boom')).toBeInTheDocument()
  })
})