import Link from 'next/link'
import EntityBadge from '@/components/common/EntityBadge'
import { explorerFeaturePages } from '@/data/explorerOperations'
import { formatUsdValue } from '@/utils/displayCurrency'
import {
  formatHoReserveCoverageLabel,
  formatSupplyNostroMatchLabel,
} from '@/utils/tokenMarket'
import { formatTimestamp } from '@/utils/format'
import OperationsPageShell from './OperationsPageShell'

export type HoLiquiditySnapshot = {
  generatedAt: string
  fineractConfigured: boolean
  cashInBank?: {
    cashInBankUsd?: number
    externalNostroGlCode?: string
    audit?: { status?: string }
    supplyNostroMatch?: {
      status?: string
      multiplier?: number
      totalSupplyUsd?: number
      externalNostroCashUsd?: number
      expectedSupplyUsd?: number
    }
  }
  reserveCoverage?: {
    status?: string
    coverageRatio?: number
    reserveAssetsUsd?: number
    requiredReserveUsd?: number
    issuedCStarUsd?: number
    reserveAssetGlCodes?: string[]
    multiplier?: number
  }
  aggregateSupplyNostroMatch?: {
    status?: string
    multiplier?: number
  }
  alerts?: Array<{ code: string; severity: string; message: string }>
  tripleState?: { aligned?: boolean; breaksCount?: number; generatedAt?: string }
  perTokenSamples?: {
    cUSDC?: {
      totalSupplyUsd?: number
      supplyNostroMatch?: { status?: string }
    }
  }
}

type HoLiquidityPageProps = {
  snapshot: HoLiquiditySnapshot | null
  loadError?: string | null
}

function formatRatio(value: number | undefined): string {
  if (value == null || !Number.isFinite(value)) return '—'
  return `${value.toFixed(2)}×`
}

export default function HoLiquidityPage({ snapshot, loadError }: HoLiquidityPageProps) {
  const page = explorerFeaturePages.hoLiquidity
  const coverage = snapshot?.reserveCoverage
  const nostro = snapshot?.cashInBank
  const aggregateMatch = snapshot?.aggregateSupplyNostroMatch ?? nostro?.supplyNostroMatch
  const cusdcSample = snapshot?.perTokenSamples?.cUSDC

  return (
    <OperationsPageShell page={page}>
      {loadError ? (
        <div className="mb-4 rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100">
          {loadError}
        </div>
      ) : null}
      {snapshot ? (
        <div className="space-y-6">
          <div className="flex flex-wrap items-center gap-3 text-sm text-gray-500 dark:text-gray-400">
            <span>Fineract audit {formatTimestamp(snapshot.generatedAt)}</span>
            <EntityBadge
              label={snapshot.fineractConfigured ? 'Fineract configured' : 'Fineract pending'}
              tone={snapshot.fineractConfigured ? 'success' : 'warning'}
            />
            {(snapshot.alerts ?? []).length === 0 ? (
              <EntityBadge label="No active alerts" tone="success" />
            ) : (
              <EntityBadge label={`${snapshot.alerts?.length ?? 0} alert(s)`} tone="warning" />
            )}
          </div>

          <div className="grid gap-4 lg:grid-cols-3">
            <section className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-700 dark:bg-gray-900/40">
              <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">Cash-in-bank</h2>
              <p className="mt-2 text-2xl font-semibold text-gray-900 dark:text-white">
                {formatUsdValue(nostro?.cashInBankUsd ?? 0)}
              </p>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                HO GL {nostro?.externalNostroGlCode ?? '13010'} nostro (Dr) — external correspondent cash, not GL 2100 M1.
              </p>
              {aggregateMatch ? (
                <div className="mt-3">
                  <EntityBadge
                    label={`Aggregate nostro match: ${formatSupplyNostroMatchLabel(aggregateMatch as never)}`}
                    tone={aggregateMatch.status === 'matched' ? 'success' : aggregateMatch.status === 'break' ? 'warning' : 'neutral'}
                  />
                </div>
              ) : null}
            </section>

            <section className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-700 dark:bg-gray-900/40">
              <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">Reserve coverage</h2>
              <p className="mt-2 text-2xl font-semibold text-gray-900 dark:text-white">
                {formatRatio(coverage?.coverageRatio)}
              </p>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                {coverage ? formatHoReserveCoverageLabel(coverage as never) : 'Unavailable'}
              </p>
              {coverage ? (
                <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
                  Reserve assets {formatUsdValue(coverage.reserveAssetsUsd ?? 0)} · required{' '}
                  {formatUsdValue(coverage.requiredReserveUsd ?? 0)} · issued c*{' '}
                  {formatUsdValue(coverage.issuedCStarUsd ?? 0)}
                </p>
              ) : null}
            </section>

            <section className="rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-700 dark:bg-gray-900/40">
              <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">PMM cash liquidity</h2>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                On-chain spendable pool depth (~$13M cUSDC-side) is shown on wallet and token pages as <strong>Cash liq.</strong> — not full DEX TVL.
              </p>
              <Link href="/tokens/0xf22258f57794CC8E06237084b353Ab30fFfa640b" className="mt-3 inline-block text-sm text-blue-600 hover:underline dark:text-blue-400">
                Open cUSDC token detail
              </Link>
            </section>
          </div>

          {cusdcSample ? (
            <section className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
              <h3 className="text-sm font-semibold text-gray-900 dark:text-white">cUSDC per-token nostro settlement</h3>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                Total supply {formatUsdValue(cusdcSample.totalSupplyUsd ?? 0)} · match{' '}
                {cusdcSample.supplyNostroMatch?.status ?? 'pending'}
              </p>
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                Per-token break is expected at current supply until nostro is scaled; aggregate reserve coverage can still be sufficient.
              </p>
            </section>
          ) : null}

          {snapshot.tripleState ? (
            <section className="rounded-2xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
              <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Triple-state reconcile</h3>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                {snapshot.tripleState.aligned ? 'Aligned' : `${snapshot.tripleState.breaksCount ?? 0} break(s)`}
                {snapshot.tripleState.generatedAt ? ` · ${formatTimestamp(snapshot.tripleState.generatedAt)}` : ''}
              </p>
            </section>
          ) : null}

          {(snapshot.alerts ?? []).length > 0 ? (
            <section className="rounded-2xl border border-gray-200 p-4 dark:border-gray-700">
              <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Alerts</h3>
              <ul className="mt-2 space-y-2 text-sm text-gray-700 dark:text-gray-300">
                {snapshot.alerts?.map((alert) => (
                  <li key={alert.code}>
                    <span className="font-medium">{alert.severity}</span> · {alert.code}: {alert.message}
                  </li>
                ))}
              </ul>
            </section>
          ) : null}
        </div>
      ) : null}
    </OperationsPageShell>
  )
}
