import type { ChainActivityContext } from '@/utils/activityContext'
import ClientRelativeTime from '@/components/common/ClientRelativeTime'
import { formatInteger } from '@/utils/format'

export default function FreshnessDetail({
  context,
  diagnosticExplanation,
  activityState,
}: {
  context: ChainActivityContext
  diagnosticExplanation?: string | null
  activityState?: string | null
}) {
  if (diagnosticExplanation) {
    return <>{diagnosticExplanation}</>
  }

  if (activityState === 'quiet_chain') {
    const latestNonEmptyBlock =
      context.last_non_empty_block_number != null ? `#${formatInteger(context.last_non_empty_block_number)}` : 'unknown'
    const blockGap =
      context.block_gap_to_latest_transaction != null
        ? `${formatInteger(context.block_gap_to_latest_transaction)} blocks`
        : 'unknown'
    return (
      <>
        Quiet-chain signal: head blocks may be empty while the chain remains current. Block gap to latest visible
        transaction: {blockGap}. Last non-empty block: {latestNonEmptyBlock}.
      </>
    )
  }

  if (context.transaction_visibility_unavailable) {
    return <>Use chain-head visibility and the last non-empty block as the current trust anchors.</>
  }

  const latestNonEmptyBlock =
    context.last_non_empty_block_number != null ? `#${formatInteger(context.last_non_empty_block_number)}` : 'unknown'
  const blockGap =
    context.block_gap_to_latest_transaction != null
      ? `${formatInteger(context.block_gap_to_latest_transaction)} blocks`
      : null

  if (context.head_is_idle) {
    return (
      <>
        Latest visible transaction: <ClientRelativeTime value={context.latest_transaction_timestamp} suffix=" ago" />. Block
        gap: {blockGap || 'unknown'}. Last non-empty block: {latestNonEmptyBlock}.
      </>
    )
  }

  if (context.state === 'active') {
    return (
      <>
        Latest visible transaction: <ClientRelativeTime value={context.latest_transaction_timestamp} suffix=" ago" />.
        Recent indexed activity remains close to the tip.
      </>
    )
  }

  return (
    <>
      Latest visible transaction: <ClientRelativeTime value={context.latest_transaction_timestamp} suffix=" ago" />. Recent
      head blocks may be quiet even while the chain remains current.
    </>
  )
}
