import { DashboardShell } from '../../../components/dashboard-shell';
import { WalletTopupForm } from '../../../components/wallet-topup-form';
import { fetchWalletSummary } from '../../../lib/api';
import { requireAuthToken } from '../../../lib/auth';
import { getLocale } from '../../../lib/i18n';

const walletLabels = {
  en: {
    title: 'Wallet & Balance',
    eyebrow: 'Billing',
    copy: 'Manage broadcast balance before messages are sent through Meta WhatsApp API.',
    availableBalance: 'Available Balance',
    heldBalance: 'Held Balance',
    totalBalance: 'Total Balance',
    broadcastRate: 'Broadcast Rate',
    perRecipient: 'per recipient',
    manualTopup: 'Manual Top Up',
    payWithMidtrans: 'Pay with Midtrans',
    manualTopupCopy: 'Minimum top up is Rp50,000. Midtrans will support QRIS, virtual account, and credit card; gateway fees are charged to the customer.',
    amount: 'Amount (IDR)',
    presetAmounts: 'Preset top up amounts',
    descriptionField: 'Description',
    processing: 'Processing...',
    failedTopup: 'Failed to top up wallet',
    topupSuccess: 'Wallet top up posted.',
    midtransCreated: 'Midtrans payment has been created.',
    transactions: 'Recent Transactions',
    type: 'Type',
    direction: 'Direction',
    amountHeader: 'Amount',
    balanceAfter: 'Balance After',
    date: 'Date',
    empty: 'No wallet transactions yet.',
    midtransTitle: 'Midtrans readiness',
    midtransCopy: 'Payment options will be limited to QRIS, bank virtual account, and credit card. The payable amount should include gateway fees charged to the customer.',
  },
  id: {
    title: 'Wallet & Saldo',
    eyebrow: 'Billing',
    copy: 'Kelola saldo broadcast sebelum pesan dikirim melalui Meta WhatsApp API.',
    availableBalance: 'Saldo Tersedia',
    heldBalance: 'Saldo Tertahan',
    totalBalance: 'Total Saldo',
    broadcastRate: 'Tarif Broadcast',
    perRecipient: 'per penerima',
    manualTopup: 'Top Up Manual',
    payWithMidtrans: 'Bayar via Midtrans',
    manualTopupCopy: 'Minimum top up Rp50.000. Midtrans nanti mendukung QRIS, virtual account bank, dan kartu kredit; fee gateway dibebankan ke nasabah.',
    amount: 'Nominal (IDR)',
    presetAmounts: 'Pilihan nominal top up',
    descriptionField: 'Deskripsi',
    processing: 'Memproses...',
    failedTopup: 'Gagal top up wallet',
    topupSuccess: 'Top up wallet berhasil dicatat.',
    midtransCreated: 'Pembayaran Midtrans berhasil dibuat.',
    transactions: 'Transaksi Terbaru',
    type: 'Tipe',
    direction: 'Arah',
    amountHeader: 'Nominal',
    balanceAfter: 'Saldo Setelah',
    date: 'Tanggal',
    empty: 'Belum ada transaksi wallet.',
    midtransTitle: 'Kesiapan Midtrans',
    midtransCopy: 'Pilihan pembayaran dibatasi ke QRIS, virtual account bank, dan kartu kredit. Nominal bayar nantinya harus sudah termasuk fee gateway yang dibebankan ke nasabah.',
  },
} as const;

function formatMoney(value: number, currency = 'IDR') {
  return new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency,
    maximumFractionDigits: 0,
  }).format(value);
}

function formatDate(value: string) {
  return new Date(value).toLocaleString('id-ID', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

export default async function WalletPage() {
  const token = await requireAuthToken();
  const locale = await getLocale();
  const labels = walletLabels[locale];
  const summary = await fetchWalletSummary(token);

  return (
    <DashboardShell currentPath="/dashboard/wallet" title={labels.title}>
      <section className="wallet-page">
        <header className="wallet-hero">
          <div>
            <p className="page-eyebrow">{labels.eyebrow}</p>
            <h1>{labels.title}</h1>
            <p>{labels.copy}</p>
          </div>
        </header>

        <section className="wallet-kpi-grid">
          <article className="wallet-kpi-card is-primary">
            <span>{labels.availableBalance}</span>
            <strong>{formatMoney(summary.wallet.availableBalanceMinor, summary.wallet.currency)}</strong>
          </article>
          <article className="wallet-kpi-card">
            <span>{labels.totalBalance}</span>
            <strong>{formatMoney(summary.wallet.balanceMinor, summary.wallet.currency)}</strong>
          </article>
          <article className="wallet-kpi-card">
            <span>{labels.heldBalance}</span>
            <strong>{formatMoney(summary.wallet.heldMinor, summary.wallet.currency)}</strong>
          </article>
          <article className="wallet-kpi-card">
            <span>{labels.broadcastRate}</span>
            <strong>{formatMoney(summary.pricing.broadcastMarketingUnitCostMinor, summary.pricing.currency)}</strong>
            <small>{labels.perRecipient}</small>
          </article>
        </section>

        <section className="wallet-layout">
          <article className="wallet-panel">
            <div className="wallet-panel-head">
              <div>
                <h2>{labels.manualTopup}</h2>
                <p>{labels.manualTopupCopy}</p>
              </div>
            </div>
            <WalletTopupForm labels={labels} />
          </article>

          <article className="wallet-panel wallet-midtrans-card">
            <span className="material-symbols-outlined">payments</span>
            <h2>{labels.midtransTitle}</h2>
            <p>{labels.midtransCopy}</p>
          </article>
        </section>

        <section className="wallet-table-card">
          <h2>{labels.transactions}</h2>
          <div className="wallet-table-wrap">
            <table className="wallet-table">
              <thead>
                <tr>
                  <th>{labels.type}</th>
                  <th>{labels.direction}</th>
                  <th>{labels.amountHeader}</th>
                  <th>{labels.balanceAfter}</th>
                  <th>{labels.date}</th>
                </tr>
              </thead>
              <tbody>
                {summary.transactions.map((transaction) => (
                  <tr key={transaction.id}>
                    <td>
                      <strong>{transaction.type.replaceAll('_', ' ')}</strong>
                      <span>{transaction.description || '-'}</span>
                    </td>
                    <td>{transaction.direction}</td>
                    <td className={transaction.direction === 'credit' ? 'is-credit' : 'is-debit'}>
                      {transaction.direction === 'credit' ? '+' : '-'}{formatMoney(transaction.amountMinor, summary.wallet.currency)}
                    </td>
                    <td>{formatMoney(transaction.balanceAfterMinor, summary.wallet.currency)}</td>
                    <td>{formatDate(transaction.createdAt)}</td>
                  </tr>
                ))}
                {summary.transactions.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="wallet-empty">{labels.empty}</td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
        </section>
      </section>
    </DashboardShell>
  );
}
