import Link from 'next/link'

import { Badge, EmptyState, Panel, PanelBody, PanelHeader, StatCard } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'
import type { CascadeResult, CascadeStep } from '@/lib/engine/cascade'

/**
 * Domino View (§6).
 *
 * A cascade is a sequence in time, so it is drawn as one: minute offsets down the rail,
 * each step naming what it did to whom and how likely the chain is to get that far.
 */
const OUTCOME_TONE: Record<CascadeStep['outcome'], string> = {
  failed: 'bg-critical',
  stressed: 'bg-watch',
  unserved: 'bg-accent',
}

const SEVERITY_TEXT: Record<CascadeStep['severity'], string> = {
  low: 'text-text-muted',
  medium: 'text-info',
  high: 'text-watch',
  critical: 'text-critical',
}

export async function CascadeTimeline({
  result,
  className,
  showStats = true,
}: {
  result: CascadeResult
  className?: string
  showStats?: boolean
}) {
  const { t, locale } = await getI18n()
  const ar = locale === 'ar'
  const propagating = result.steps.filter((step) => step.depth > 0)

  return (
    <div className={className}>
      {showStats ? (
        <div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <StatCard
            label={t('cascade.affectedAssets')}
            value={formatNumber(locale, result.affectedAssets)}
            state={result.affectedAssets > 3 ? 'critical' : result.affectedAssets > 1 ? 'warning' : 'normal'}
          />
          <StatCard
            label={t('cascade.affectedCustomers')}
            value={formatNumber(locale, result.affectedCustomers)}
          />
          <StatCard
            label={t('cascade.depth')}
            value={formatNumber(locale, result.maxDepth)}
            hint={`${t('cascade.contained')} +${formatNumber(locale, result.containedAtMin ?? 0)} ${t('common.minutes')}`}
          />
          <StatCard
            label={t('cascade.regionalRisk')}
            value={formatNumber(locale, result.regionalRisk, { maximumFractionDigits: 0 })}
            unit="%"
            state={result.regionalRisk >= 60 ? 'critical' : result.regionalRisk >= 35 ? 'warning' : 'normal'}
          />
        </div>
      ) : null}

      <Panel>
        <PanelHeader
          title={t('cascade.timeline')}
          subtitle={result.originCode}
          action={
            result.unservedMw > 0 ? (
              <Badge tone="accent">
                {t('cascade.unserved')} {formatNumber(locale, result.unservedMw)} MW
              </Badge>
            ) : null
          }
        />
        {propagating.length === 0 ? (
          <EmptyState title={t('cascade.empty')} />
        ) : (
          <PanelBody className="pt-0">
            <ol className="relative space-y-4 pt-3">
              <span
                aria-hidden
                className="absolute inset-y-2 w-px bg-border"
                style={{ insetInlineStart: '2.9rem' }}
              />
              {result.steps.map((step) => (
                <li key={`${step.ordinal}-${step.assetCode}`} className="relative flex items-start gap-3">
                  <span className="tnum w-10 shrink-0 pt-0.5 text-end text-[11px] font-medium text-text-faint">
                    +{formatNumber(locale, step.offsetMin)}
                  </span>
                  <span
                    aria-hidden
                    className={cn(
                      'mt-1.5 size-2.5 shrink-0 rounded-full ring-4 ring-surface',
                      OUTCOME_TONE[step.outcome],
                    )}
                  />
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
                      <div className="flex flex-wrap items-center gap-2">
                        <Link
                          href={`/assets/${encodeURIComponent(step.assetCode)}`}
                          className="font-mono text-xs font-medium text-text transition-colors hover:text-brand"
                        >
                          {step.assetCode}
                        </Link>
                        <span className="text-[11px] text-text-muted">
                          {ar ? step.assetNameAr : step.assetName}
                        </span>
                      </div>
                      <span className={cn('text-[10px] font-medium', SEVERITY_TEXT[step.severity])}>
                        {t(`cascade.outcome.${step.outcome}`)}
                      </span>
                    </div>
                    <p className="mt-1 text-[11px] text-text-muted">
                      {t(`cascade.mechanism.${step.mechanism}`)}
                      {step.transferredMw > 0
                        ? ` · ${formatNumber(locale, step.transferredMw)} MW`
                        : ''}
                      {step.loadPctAfter > 0
                        ? ` · ${formatNumber(locale, step.loadPctAfter, { maximumFractionDigits: 0 })}%`
                        : ''}
                      {` · ${t('cascade.probability')} ${formatNumber(locale, step.probability * 100, { maximumFractionDigits: 0 })}%`}
                    </p>
                  </div>
                </li>
              ))}
            </ol>
          </PanelBody>
        )}
      </Panel>
    </div>
  )
}
