'use client'

import { Card } from '@/libs/frontend-ui-primitives'
import EntityBadge from '@/components/common/EntityBadge'
import ClientRelativeTime from '@/components/common/ClientRelativeTime'
import type { MissionControlMode } from '@/services/api/missionControl'

const REASON_LABELS: Record<string, string> = {
  live_homepage_stream_not_attached: 'Live homepage stream is not attached; relay posture uses snapshot polling.',
  relay_snapshot_only_source: 'Relay monitoring uses snapshot sources while other explorer feeds remain live.',
  partial_observability_inputs: 'Some freshness inputs are partial, so posture is reported conservatively.',
}

const SCOPE_LABELS: Record<string, string> = {
  relay_monitoring_homepage_card_only: 'Affects relay monitoring and the homepage mission card only.',
  bridge_monitoring_and_homepage: 'Affects bridge monitoring and homepage summary surfaces.',
  homepage_summary_only: 'Affects homepage summary messaging only.',
}

function humanizeKey(value?: string | null): string {
  if (!value) return 'Not specified'
  return SCOPE_LABELS[value] || REASON_LABELS[value] || value.replaceAll('_', ' ')
}

function modeTone(kind?: string | null): 'success' | 'warning' | 'info' | 'neutral' {
  switch (String(kind || '').toLowerCase()) {
    case 'live':
      return 'success'
    case 'mixed':
      return 'warning'
    case 'snapshot':
      return 'info'
    default:
      return 'neutral'
  }
}

export default function MissionDeliveryModePanel({
  mode,
  title = 'Delivery mode',
  className = '',
}: {
  mode?: MissionControlMode | null
  title?: string
  className?: string
}) {
  if (!mode?.kind) return null

  const normalizedClassName = className ? ` ${className}` : ''

  return (
    <Card
      className={`border border-indigo-200 bg-indigo-50/60 dark:border-indigo-900/40 dark:bg-indigo-950/20${normalizedClassName}`}
      title={title}
    >
      <div className="flex flex-col gap-3">
        <div className="flex flex-wrap items-center gap-2">
          <EntityBadge label={`mode ${mode.kind}`} tone={modeTone(mode.kind)} />
          {mode.updated_at ? (
            <span className="text-xs text-gray-600 dark:text-gray-400">
              Updated <ClientRelativeTime value={mode.updated_at} suffix=" ago" />
            </span>
          ) : null}
        </div>
        {mode.reason ? (
          <p className="text-sm leading-6 text-gray-700 dark:text-gray-300">
            <span className="font-medium text-gray-900 dark:text-white">Reason:</span> {humanizeKey(String(mode.reason))}
          </p>
        ) : null}
        {mode.scope ? (
          <p className="text-sm leading-6 text-gray-700 dark:text-gray-300">
            <span className="font-medium text-gray-900 dark:text-white">Scope:</span> {humanizeKey(String(mode.scope))}
          </p>
        ) : null}
      </div>
    </Card>
  )
}
