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

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

const getInventory = vi.fn()
const getSuppliers = vi.fn()

vi.mock('@/lib/api/agent', async importOriginal => {
  const actual = await importOriginal<typeof import('@/lib/api/agent')>()
  return {
    ...actual,
    getInventory: (...args: unknown[]) => getInventory(...args),
    getSuppliers: (...args: unknown[]) => getSuppliers(...args),
  }
})

function makeItem(overrides: Partial<Record<string, unknown>> & { id: string }) {
  return {
    business_id: '11111111-1111-1111-1111-111111111111',
    quantity: 20,
    reserved_quantity: 0,
    location: 'Main Store',
    updated_at: '2026-08-21T00:00:00Z',
    ...overrides,
  }
}

const items = [
  makeItem({
    id: 'inv-bag',
    product_id: '30000000-0000-0000-0000-000000000001',
    quantity: 20,
    product: { id: '30000000-0000-0000-0000-000000000001', name: 'Laptop Bag', sku: 'KSB-BAG-001', unit_price: 25, reorder_threshold: 5 },
  }),
  makeItem({
    id: 'inv-kbd',
    product_id: '30000000-0000-0000-0000-000000000003',
    quantity: 5,
    product: { id: '30000000-0000-0000-0000-000000000003', name: 'USB Keyboard', sku: 'KSB-KBD-003', unit_price: 18, reorder_threshold: 6 },
  }),
  makeItem({
    id: 'inv-mouse',
    product_id: '30000000-0000-0000-0000-000000000002',
    quantity: 0,
    product: { id: '30000000-0000-0000-0000-000000000002', name: 'Wireless Mouse', sku: 'KSB-MSE-002', unit_price: 12.5, reorder_threshold: 8 },
  }),
]

beforeEach(() => {
  vi.clearAllMocks()
  getInventory.mockResolvedValue({ success: true, data: { items } })
  getSuppliers.mockResolvedValue({
    success: true,
    data: {
      items: [
        {
          id: 'sp-1',
          supplier_id: '40000000-0000-0000-0000-000000000004',
          product_id: '30000000-0000-0000-0000-000000000002',
          unit_cost: 8.5,
          available_quantity: 20,
          delivery_days: 1,
          last_updated: '2026-08-21T00:00:00Z',
          supplier: { id: '40000000-0000-0000-0000-000000000004', name: 'Global Gadgets', reliability_score: 0.85 },
        },
      ],
    },
  })
})

async function renderPage() {
  render(<InventoryPage />)
  await waitFor(() => expect(screen.getByText('Laptop Bag')).toBeInTheDocument())
}

describe('InventoryPage status rendering', () => {
  it('renders Available, Low Stock and Out of Stock badges using availability math', async () => {
    await renderPage()
    // each status label appears at least twice: filter chip + row badge (+ KPI card)
    expect(screen.getAllByText('Available').length).toBeGreaterThanOrEqual(2)
    expect(screen.getAllByText('Low Stock').length).toBeGreaterThanOrEqual(2)
    expect(screen.getAllByText('Out of Stock').length).toBeGreaterThanOrEqual(2)
    expect(getInventory).toHaveBeenCalled()
  })

  it('shows reserved and available columns separately', async () => {
    await renderPage()
    expect(screen.getByText('Reserved')).toBeInTheDocument()
    expect(screen.getAllByText('Available').length).toBeGreaterThanOrEqual(1)
  })
})

describe('InventoryPage filtering', () => {
  it('narrows rows to the selected status', async () => {
    await renderPage()
    fireEvent.click(screen.getByRole('button', { name: 'Out of Stock' }))
    expect(screen.getByText('Wireless Mouse')).toBeInTheDocument()
    expect(screen.queryByText('Laptop Bag')).not.toBeInTheDocument()
    expect(screen.queryByText('USB Keyboard')).not.toBeInTheDocument()

    fireEvent.click(screen.getByRole('button', { name: 'Low Stock' }))
    expect(screen.getByText('USB Keyboard')).toBeInTheDocument()
    expect(screen.queryByText('Wireless Mouse')).not.toBeInTheDocument()

    fireEvent.click(screen.getByRole('button', { name: 'All' }))
    expect(screen.getByText('Laptop Bag')).toBeInTheDocument()
    expect(screen.getByText('Wireless Mouse')).toBeInTheDocument()
  })

  it('shows empty state when filter matches nothing', async () => {
    await renderPage()
    fireEvent.click(screen.getByRole('button', { name: 'Available' }))
    fireEvent.change(screen.getByLabelText('Search products'), { target: { value: 'zzz-not-found' } })
    await waitFor(() => expect(screen.getByText('No products found')).toBeInTheDocument())
  })
})

describe('InventoryPage supplier inspection', () => {
  it('expands a low-stock row to show supplier options', async () => {
    await renderPage()
    fireEvent.click(screen.getByText('USB Keyboard'))
    await waitFor(() => expect(getSuppliers).toHaveBeenCalledTimes(1))
    // Keyboard has no offerings -> hint shown
    await waitFor(() =>
      expect(screen.getByText(/No supplier offers found/i)).toBeInTheDocument()
    )
  })

  it('shows supplier offers for an out-of-stock product', async () => {
    await renderPage()
    fireEvent.click(screen.getByText('Wireless Mouse'))
    await waitFor(() => expect(screen.getByText('Global Gadgets')).toBeInTheDocument())
    expect(screen.getByText('$8.50/unit')).toBeInTheDocument()
  })
})
