import { useEffect, useState } from 'react'
import { finance } from '@/api/client'
import type { JournalEntry } from '@/types/api'
import { PageHeader } from '@/components/PageHeader'
import { Loading } from '@/components/Loading'
import { ErrorBox } from '@/components/ErrorBox'
import { DataTable, type Column } from '@/components/DataTable'
import { StatusBadge } from '@/components/StatusBadge'

export function JournalEntriesPage() {
  const [rows, setRows] = useState<JournalEntry[]>([])
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    finance
      .listJournalEntries()
      .then((rs) =>
        setRows([...rs].sort((a, b) => (b.postedAt ?? '').localeCompare(a.postedAt ?? ''))),
      )
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }, [])

  const columns: Column<JournalEntry>[] = [
    {
      header: 'Posted',
      key: 'postedAt',
      render: (r) => (r.postedAt ? new Date(r.postedAt).toLocaleString() : '—'),
    },
    { header: 'Code', key: 'code', render: (r) => <span className="font-mono text-xs">{r.code}</span> },
    { header: 'Type', key: 'type' },
    { header: 'Status', key: 'status', render: (r) => <StatusBadge status={r.status} /> },
    { header: 'Order', key: 'orderCode', render: (r) => <span className="font-mono">{r.orderCode}</span> },
    { header: 'Partner', key: 'partnerCode', render: (r) => <span className="font-mono">{r.partnerCode}</span> },
    {
      header: 'Amount',
      key: 'amount',
      render: (r) => (
        <span className="font-mono tabular-nums">
          {Number(r.amount).toLocaleString(undefined, { minimumFractionDigits: 2 })}{' '}
          {r.currencyCode}
        </span>
      ),
    },
  ]

  return (
    <div>
      <PageHeader
        title="Journal Entries"
        subtitle="AR / AP entries created reactively by pbc-finance from order lifecycle events."
      />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
