import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import PlatformBusinessDetailPage from '@/app/platform/businesses/[id]/page'

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

vi.mock('next/navigation', () => ({
  useParams: () => ({ id: '11111111-1111-1111-1111-111111111111' }),
  useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
  usePathname: () => '/platform/businesses/x',
}))

const detailFixture = (overrides: Record<string, unknown> = {}) => ({
  success: true as const,
  data: {
    business: {
      id: '11111111-1111-1111-1111-111111111111',
      name: 'Kigali Smart Supplies',
      slug: 'kigali-smart-supplies',
      industry: 'Technology',
      currency: 'RWF',
      country: 'Rwanda',
      status: 'active' as const,
      payment_enabled: true,
      payment_phone: '+250 788 000 111',
      store_published: true,
      owner_id: 'o-1',
      created_at: '2026-08-01T00:00:00Z',
      updated_at: '2026-08-29T00:00:00Z',
    },
    metrics: {
      products: 12,
      low_stock_items: 2,
      orders_total: 34,
      orders_by_status: { completed: 30, pending: 4 },
      pending_approvals: 1,
      members: 2,
      invoices: 7,
      suppliers: 3,
    },
    ai_activity: {
      tasks_total: 10,
      tasks_by_status: { completed: 8, awaiting_approval: 2 },
      actions_total: 5,
      recent_tasks: [
        { id: 't1', task_type: 'inventory_restock', status: 'completed', started_at: '2026-08-29T10:00:00Z', scheduled_for: '2026-08-29T09:30:00Z' },
        { id: 't2', task_type: 'purchase_request', status: 'awaiting_approval', started_at: '2026-08-29T11:00:00Z', scheduled_for: '2026-08-29T10:30:00Z' },
      ],
    },
    members: [
      { id: 'm1', full_name: 'Owner A', role: 'admin', status: 'active', created_at: '', email: 'owner@kigalismart.rw' },
      { id: 'm2', full_name: 'Jean', role: 'stock_keeper', status: 'active', created_at: '', email: null },
    ],
    invites: [],
    recent_audit: [],
    ...overrides,
  },
})

vi.mock('@/lib/api/platform', () => ({
  getPlatformBusiness: vi.fn(),
  setBusinessStatus: vi.fn(),
  exportBusinessData: vi.fn(),
}))

import { getPlatformBusiness, setBusinessStatus } from '@/lib/api/platform'

beforeEach(() => {
  vi.clearAllMocks()
  vi.mocked(getPlatformBusiness).mockResolvedValue(detailFixture() as never)
  vi.mocked(setBusinessStatus).mockResolvedValue({
    success: true,
    data: { business_id: 'x', status: 'suspended' },
  } as never)
})

describe('PlatformBusinessDetailPage', () => {
  it('shows invoices and suppliers alongside the existing metrics', async () => {
    render(<PlatformBusinessDetailPage />)
    expect(await screen.findByText('Kigali Smart Supplies')).toBeInTheDocument()
    expect(screen.getByText('Invoices')).toBeInTheDocument()
    expect(screen.getAllByText('7').length).toBeGreaterThan(0)
    expect(screen.getAllByText('Suppliers').length).toBeGreaterThan(0)
    expect(screen.getAllByText('3').length).toBeGreaterThan(0)
    expect(screen.getAllByText('12').length).toBeGreaterThan(0)
    expect(screen.getAllByText('34').length).toBeGreaterThan(0)
  })

  it('shows AI operations activity with recent runs', async () => {
    render(<PlatformBusinessDetailPage />)
    expect(await screen.findByText('AI operations')).toBeInTheDocument()
    expect(screen.getByText('Tasks (all-time):')).toBeInTheDocument()
    expect(screen.getAllByText('10').length).toBeGreaterThan(0)
    expect(screen.getByText('Agent actions (all-time):')).toBeInTheDocument()
    expect(screen.getAllByText('5').length).toBeGreaterThan(0)
    expect(screen.getByText('inventory_restock')).toBeInTheDocument()
    expect(screen.getByText('purchase_request')).toBeInTheDocument()
  })

  it('renders an empty state when there is no AI activity', async () => {
    vi.mocked(getPlatformBusiness).mockResolvedValue(
      detailFixture({
        ai_activity: { tasks_total: 0, tasks_by_status: {}, actions_total: 0, recent_tasks: [] },
      }) as never
    )
    render(<PlatformBusinessDetailPage />)
    expect(await screen.findByText('AI operations')).toBeInTheDocument()
    expect(screen.getByText('No AI operations recorded yet.')).toBeInTheDocument()
  })

  it('lists member emails (or marks them missing)', async () => {
    render(<PlatformBusinessDetailPage />)
    expect(await screen.findByText('Owner A')).toBeInTheDocument()
    expect(screen.getByRole('link', { name: 'owner@kigalismart.rw' })).toHaveAttribute(
      'href',
      'mailto:owner@kigalismart.rw'
    )
    expect(screen.getByText('No email on file')).toBeInTheDocument()
  })

  it('suspends the business and refreshes the view', async () => {
    render(<PlatformBusinessDetailPage />)
    fireEvent.click(await screen.findByRole('button', { name: /suspend/i }))
    await waitFor(() => expect(setBusinessStatus).toHaveBeenCalledWith(
      '11111111-1111-1111-1111-111111111111',
      'suspended'
    ))
  })
})