import { TrendingDown, Calendar, DollarSign, Percent } from 'lucide-react'
import { formatCurrency, formatPayback, formatPercent } from '@/lib/format'
import type { RoiResult } from '@/domain/roi'

interface RoiKpiBarProps {
  roi: RoiResult
  currency: string
  horizonYears: number
}

function RoiKpiHero({
  label, value, sub,
}: {
  label: string
  value: string
  sub?: string
}) {
  return (
    <div
      data-testid="roi-kpi-card"
      className="rounded-xl p-5 mb-4"
      style={{ background: 'linear-gradient(135deg, #F59845 0%, #ED3E8F 100%)' }}
    >
      <p className="text-xs font-semibold text-white/90 uppercase tracking-widest mb-1">{label}</p>
      <p className="text-3xl font-bold font-mono text-white leading-tight" style={{ letterSpacing: '-0.5px' }}>
        {value}
      </p>
      {sub && <p className="text-sm text-white/85 mt-1">{sub}</p>}
    </div>
  )
}

function RoiKpiCard({
  label, value, sub, icon, iconColor, valueColor, compact,
}: {
  label: string
  value: string
  sub?: string
  icon: React.ReactNode
  iconColor: string
  valueColor?: string
  compact?: boolean
}) {
  return (
    <div data-testid="roi-kpi-card" className="bg-white rounded-xl border border-slate-200 shadow-sm p-4 flex items-start gap-3">
      <div className={`shrink-0 p-2.5 rounded-lg ${iconColor}`}>
        {icon}
      </div>
      <div className="min-w-0 flex-1">
        <p className="text-xs font-medium text-slate-500 uppercase tracking-wide mb-1">{label}</p>
        <p className={`${compact ? 'text-sm' : 'text-xl'} font-bold font-mono leading-tight ${valueColor ?? 'text-slate-900'}`}>{value}</p>
        {sub && <p className="text-xs text-slate-400 mt-0.5 leading-snug">{sub}</p>}
      </div>
    </div>
  )
}

export function RoiKpiBar({ roi, currency, horizonYears }: RoiKpiBarProps) {
  const paybackStr = formatPayback(roi.paybackMonths)

  const roiIsUndefined = !isFinite(roi.roiAnnualPercent)
  const roiStr = roiIsUndefined ? '—' : formatPercent(roi.roiAnnualPercent)
  const roiSub = roiIsUndefined
    ? 'Configurá la inversión del proyecto en Configuración Global'
    : 'retorno anual sobre la inversión'

  const savingsPosColor = roi.savingsPerExecution > 0
    ? 'text-emerald-700'
    : roi.savingsPerExecution < 0
    ? 'text-red-600'
    : 'text-slate-900'

  const annualPosColor = roi.annualSavings > 0
    ? 'text-emerald-700'
    : roi.annualSavings < 0
    ? 'text-red-600'
    : 'text-slate-900'

  const cumulativeSub = roi.cumulativeSavingsHorizon > 0
    ? `neto de inversión inicial · ${horizonYears} años`
    : 'sin recuperación neta en el horizonte'

  return (
    <div className="mb-8">
      {/* KPI Hero — Ahorro proyectado a N años */}
      <RoiKpiHero
        label={`Ahorro proyectado a ${horizonYears} años`}
        value={formatCurrency(roi.cumulativeSavingsHorizon, currency)}
        sub={cumulativeSub}
      />

      {/* KPIs secundarios — grid 4 columnas */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <RoiKpiCard
          label="Ahorro por ejecución"
          value={formatCurrency(roi.savingsPerExecution, currency)}
          sub={`${formatPercent(roi.savingsPerExecutionPercent)} vs. escenario actual`}
          icon={<TrendingDown className="h-4 w-4 text-emerald-600" />}
          iconColor="bg-emerald-50"
          valueColor={savingsPosColor}
        />
        <RoiKpiCard
          label="Ahorro anual"
          value={formatCurrency(roi.annualSavings, currency)}
          sub="sobre la frecuencia configurada"
          icon={<DollarSign className="h-4 w-4 text-emerald-600" />}
          iconColor="bg-emerald-50"
          valueColor={annualPosColor}
        />
        <RoiKpiCard
          label="Payback"
          value={paybackStr}
          sub={roi.breaksEvenInHorizon ? '✓ Dentro del horizonte' : 'Fuera del horizonte de análisis'}
          icon={<Calendar className="h-4 w-4 text-primary" />}
          iconColor="bg-primary/10"
          valueColor={roi.breaksEvenInHorizon ? 'text-emerald-700' : 'text-slate-900'}
          compact
        />
        <RoiKpiCard
          label="ROI anual"
          value={roiStr}
          sub={roiSub}
          icon={<Percent className="h-4 w-4 text-amber-600" />}
          iconColor="bg-amber-50"
          valueColor={roiIsUndefined ? 'text-slate-400' : roi.roiAnnualPercent > 0 ? 'text-emerald-700' : roi.roiAnnualPercent < 0 ? 'text-red-600' : 'text-slate-900'}
        />
      </div>
    </div>
  )
}
