import type { AnalyticsFinanceReportDto } from '@navi/types';
import { formatMoney, formatNumber } from '@navi/ui';
import { AccessDenied } from '../../../components/AccessDenied';
import { EmptyState, MetricCard, Notice, NotAvailable, PageHeader, StatusBadge } from '../../../components/DashboardPrimitives';
import { dashboardApi } from '../../../lib/api';
import { fetchAnalyticsFinanceReport } from '../../../lib/analyticsApi';
import type { DashboardOverview } from '../../../lib/dashboardTypes';
import { requireDashboardRoute } from '../../../lib/permissions';

export default async function Reports() {
  const gate = await requireDashboardRoute('/reports');
  if (!gate.allowed) return <AccessDenied required={gate.required} />;
  const [overview, financeResult] = await Promise.all([
    dashboardApi<DashboardOverview>('/dashboard/overview'),
    fetchAnalyticsFinanceReport(),
  ]);
  const finance = financeResult.status === 'ok' ? financeResult.data : null;

  return (
    <div className="stack">
      <PageHeader
        title="Reports"
        eyebrow="Finance summary"
        description="Real payment, refund, payout, and commission-readiness reporting from the API. Commission revenue is not estimated until a commission ledger/rate model exists."
      />
      {financeResult.status === 'forbidden' ? (
        <Notice tone="error" title="Finance report permission denied" body="This session can see the reports shell but not global analytics finance reporting." />
      ) : null}
      {financeResult.status === 'error' ? (
        <Notice tone="error" title="Finance report unavailable" body={financeResult.message} />
      ) : null}
      {overview ? (
        <div className="metric-grid">
          <MetricCard label="Payment intents" value={overview.metrics.paymentIntentCount == null ? <NotAvailable /> : formatNumber(overview.metrics.paymentIntentCount)} />
          <MetricCard label="Intent total" value={overview.metrics.paymentIntentTotal ? formatMoney(overview.metrics.paymentIntentTotal, 'en') : <NotAvailable />} />
          <MetricCard label="Requested refunds" value={overview.metrics.requestedRefunds == null ? <NotAvailable /> : formatNumber(overview.metrics.requestedRefunds)} />
          <MetricCard label="Bookings this week" value={overview.metrics.bookingsThisWeek == null ? <NotAvailable /> : formatNumber(overview.metrics.bookingsThisWeek)} />
        </div>
      ) : (
        <EmptyState title="No report data available" body="The API did not expose finance metrics for this session." />
      )}
      {finance ? <FinanceReport report={finance} /> : null}
    </div>
  );
}

function FinanceReport({ report }: { report: AnalyticsFinanceReportDto }) {
  return (
    <>
      <section className="metric-grid">
        <MetricCard label="Captured payments" value={formatMinor(report.payments.capturedMinor, report.currencyCode)} hint={`${formatNumber(report.payments.count)} total payment intents`} />
        <MetricCard label="Refund exposure" value={formatMinor(report.refunds.totalMinor, report.currencyCode)} hint={`${formatNumber(report.refunds.requestedCount)} requested refund(s)`} />
        <MetricCard label="Pending payouts" value={formatMinor(report.payouts.pendingMinor, report.currencyCode)} hint={`${formatNumber(report.payouts.count)} payout record(s)`} />
        <MetricCard label="Commission status" value="Pending" hint={report.commission.modelStatus.replace(/_/g, ' ').toLowerCase()} />
      </section>

      <section className="two-col">
        <div className="card stack">
          <h3 style={{ margin: 0 }}>Money operations</h3>
          <div className="table-wrap">
            <table className="table">
              <thead><tr><th>Area</th><th>Status</th><th>Count</th><th>Total</th></tr></thead>
              <tbody>
                {report.payments.byStatus.map((row) => (
                  <tr key={`payment-${row.key}`}>
                    <td>Payments</td>
                    <td><StatusBadge value={row.key} /></td>
                    <td>{formatNumber(row.count)}</td>
                    <td>{formatMinor(row.totalMinor, report.currencyCode)}</td>
                  </tr>
                ))}
                {report.refunds.byStatus.map((row) => (
                  <tr key={`refund-${row.key}`}>
                    <td>Refunds</td>
                    <td><StatusBadge value={row.key} /></td>
                    <td>{formatNumber(row.count)}</td>
                    <td>{formatMinor(row.totalMinor, report.currencyCode)}</td>
                  </tr>
                ))}
                {report.payouts.byStatus.map((row) => (
                  <tr key={`payout-${row.key}`}>
                    <td>Payouts</td>
                    <td><StatusBadge value={row.key} /></td>
                    <td>{formatNumber(row.count)}</td>
                    <td>{formatMinor(row.totalMinor, report.currencyCode)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="stack">
          <div className="card stack">
            <h3 style={{ margin: 0 }}>Risk queue</h3>
            <RiskRow label="Unpaid bookings" value={report.risk.unpaidBookingCount} />
            <RiskRow label="Failed payments" value={report.risk.failedPaymentCount} />
            <RiskRow label="Requested refunds" value={report.risk.requestedRefundCount} />
            <RiskRow label="Pending payouts" value={report.risk.pendingPayoutCount} />
            <RiskRow label="Production payment providers" value={report.risk.productionPaymentProviderCount} />
          </div>
          <Notice
            tone="info"
            title="Commission reporting readiness"
            body={`${report.commission.commissionEnabledProviderCount} provider integration(s) have commission enabled; ${report.commission.productionLiveCommissionProviderCount} are production live. ${report.commission.note}`}
          />
        </div>
      </section>
    </>
  );
}

function RiskRow({ label, value }: { label: string; value: number }) {
  return (
    <div className="button-row" style={{ justifyContent: 'space-between' }}>
      <span className="muted">{label}</span>
      <strong>{formatNumber(value)}</strong>
    </div>
  );
}

function formatMinor(amountMinor: number, currencyCode: string) {
  return formatMoney({ amountMinor, currencyCode }, 'en');
}
