'use client'

import type { ComponentRenderProps } from '@json-render/react'

type LineItem = {
  name: string; description?: string; quantity: number; unitPrice: number; total: number
}

function fmt(n: number, currency: string) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(n)
}

export function LineItemsTable({ element }: ComponentRenderProps) {
  const { items, currency = 'USD' } = element.props as { items: LineItem[]; currency?: string }

  return (
    <div className="bg-white rounded-xl shadow-sm overflow-hidden mb-5">
      <table className="w-full">
        <thead>
          <tr>
            <th className="bg-gray-50 px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider border-b border-gray-200">Item</th>
            <th className="bg-gray-50 px-4 py-3 text-center text-xs font-semibold text-gray-500 uppercase tracking-wider border-b border-gray-200">Qty</th>
            <th className="bg-gray-50 px-4 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider border-b border-gray-200">Price</th>
            <th className="bg-gray-50 px-4 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider border-b border-gray-200">Total</th>
          </tr>
        </thead>
        <tbody>
          {items.map((item, i) => (
            <tr key={i} className="border-b border-gray-50 last:border-b-0">
              <td className="px-4 py-4">
                <div className="font-medium text-gray-900">{item.name}</div>
                {item.description && <div className="text-sm text-gray-500 mt-0.5">{item.description}</div>}
              </td>
              <td className="px-4 py-4 text-center text-gray-500">{item.quantity}</td>
              <td className="px-4 py-4 text-right font-mono text-gray-900">{fmt(item.unitPrice, currency)}</td>
              <td className="px-4 py-4 text-right font-mono text-gray-900">{fmt(item.total, currency)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
