'use client'

import { useI18n } from '@/components/providers/i18n-provider'
import { useLiveGrid } from '@/components/providers/live-grid-provider'
import { StatCard } from '@/components/ui/display'
import { cn } from '@/lib/cn'
import { riskToState } from '@/lib/domain/enums'

/**
 * The Command Center headline tiles.
 *
 * They read from the shared live stream, so all ten update on the same tick and can
 * never disagree with each other — a dashboard where the load tile and the reserve tile
 * come from different moments is worse than one that updates less often.
 */
export function LiveStatCards({
  staticCards,
}: {
  staticCards: {
    activeAlerts: number
    predictedFailures: number
    preventedFailures: number
    downtimeAvoidedHours: number
    co2AvoidedTons: number
  }
}) {
  const { t, mw, n, pct } = useI18n()
  const { snapshot } = useLiveGrid()

  if (!snapshot) {
    return (
      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
        {Array.from({ length: 10 }).map((_, index) => (
          <div key={index} className="h-28 animate-pulse rounded-[--radius-panel] border border-border bg-surface/50" />
        ))}
      </div>
    )
  }

  const stabilityState = riskToState(100 - snapshot.stabilityIndex)

  const inputs = snapshot.integrations

  return (
    <>
      {/*
        The inputs, on the same tick as the outputs (4.1). Deliberately a strip rather
        than a twelfth tile: it is not another measurement of the grid, it is the answer to
        whether the measurements below can be trusted at all.
      */}
      <a
        href="/integrations"
        title={t('commandCenter.inputHealthNote')}
        data-testid="input-health"
        className="mb-3 flex flex-wrap items-center gap-x-6 gap-y-1 rounded-[--radius-panel] border border-border bg-surface-2/40 px-4 py-2.5 text-[11px] transition-colors hover:border-brand/30"
      >
        <span className="font-medium text-text-muted">{t('commandCenter.inputHealth')}</span>
        <span>
          <span className="text-text-faint">{t('commandCenter.sourcesDelivering')}: </span>
          <span
            className={cn(
              'font-mono tabular-nums',
              inputs.disconnected > 0 ? 'text-warning' : 'text-normal',
            )}
          >
            {n(inputs.connected)}/{n(inputs.sources)}
          </span>
        </span>
        <span>
          <span className="text-text-faint">{t('commandCenter.inputQuality')}: </span>
          <span className="font-mono tabular-nums text-text">{pct(inputs.meanQuality, 1)}</span>
        </span>
        {inputs.weakestSource ? (
          <span>
            <span className="text-text-faint">{t('commandCenter.weakestSource')}: </span>
            <span className="font-mono tabular-nums text-text-muted">
              {inputs.weakestSource.code} · {pct(inputs.weakestSource.quality, 1)}
            </span>
          </span>
        ) : null}
      </a>

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
      <StatCard
        label={t('commandCenter.cards.totalLoad')}
        value={mw(snapshot.totalLoadMw)}
        unit={t('common.units.mw')}
        hint={t('commandCenter.loadRatio') + ' · ' + pct(snapshot.loadRatio * 100, 1)}
        emphasis
      />
      <StatCard
        label={t('commandCenter.cards.availableCapacity')}
        value={mw(snapshot.availableCapacityMw)}
        unit={t('common.units.mw')}
        hint={t('commandCenter.reserveMargin') + ' · ' + pct(snapshot.reserveMarginPct, 1)}
      />
      <StatCard
        label={t('commandCenter.cards.renewableGeneration')}
        value={mw(snapshot.renewableMw)}
        unit={t('common.units.mw')}
        hint={`${pct(snapshot.renewableSharePct, 1)} ${t('renewables.current').toLowerCase()}`}
        href="/renewables"
      />
      <StatCard
        label={t('commandCenter.cards.gridStability')}
        value={n(snapshot.stabilityIndex, { maximumFractionDigits: 1 })}
        state={stabilityState}
        hint={`${t('commandCenter.frequency')} ${n(snapshot.frequencyHz, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ${t('common.units.hz')}`}
        href="/grid"
      />
      <StatCard
        label={t('commandCenter.cards.activeAlerts')}
        value={n(staticCards.activeAlerts)}
        state={staticCards.activeAlerts > 0 ? 'warning' : 'normal'}
        href="/alerts"
      />
      <StatCard
        label={t('commandCenter.cards.criticalAssets')}
        value={n(snapshot.criticalCount)}
        state={snapshot.criticalCount > 0 ? 'critical' : 'normal'}
        hint={`${n(snapshot.warningCount)} ${t('states.warning').toLowerCase()}`}
        href="/assets"
      />
      <StatCard
        label={t('commandCenter.cards.predictedFailures')}
        value={n(staticCards.predictedFailures)}
        state={staticCards.predictedFailures > 0 ? 'warning' : 'normal'}
        href="/predictions"
      />
      <StatCard
        label={t('commandCenter.cards.preventedFailures')}
        value={n(staticCards.preventedFailures)}
        state="normal"
        hint={t('common.demoEstimate')}
      />
      <StatCard
        label={t('commandCenter.cards.downtimeAvoided')}
        value={n(staticCards.downtimeAvoidedHours, { maximumFractionDigits: 0 })}
        unit={t('common.units.hours')}
        hint={t('common.demoEstimate')}
      />
      <StatCard
        label={t('commandCenter.cards.co2Avoided')}
        value={n(staticCards.co2AvoidedTons, { maximumFractionDigits: 0 })}
        unit={t('common.units.tons')}
        hint={t('common.demoEstimate')}
      />
      </div>
    </>
  )
}
