'use client'
// tdd-guard:skip — presentational component; status-color logic lives in lib/oee/colors.ts (tested).

import { OeeInput, OeeResult, formatMinutesAsHours, formatPercent } from '@/lib/oee/engine'
import { oeeColorVar, OEE_THRESHOLDS } from '@/lib/oee/colors'
import FormulaTooltip from '@/components/ui/formula-tooltip'

interface Props {
  input: OeeInput
  result: OeeResult
}

function Badge({
  value,
  color,
  tooltipLabel,
  tooltipFormula,
  tooltipExample,
}: {
  value: string
  color: string
  tooltipLabel?: string
  tooltipFormula?: string
  tooltipExample?: string
}) {
  const inner = (
    <span
      className="text-xs font-mono font-semibold px-2 py-0.5 rounded-md"
      style={{
        color,
        backgroundColor: `color-mix(in srgb, ${color} 9%, transparent)`,
        border: `1px solid color-mix(in srgb, ${color} 19%, transparent)`,
      }}
    >
      {value}
    </span>
  )
  if (tooltipLabel && tooltipFormula && tooltipExample) {
    return (
      <FormulaTooltip label={tooltipLabel} formula={tooltipFormula} example={tooltipExample}>
        {inner}
      </FormulaTooltip>
    )
  }
  return inner
}

function CascadeBox({
  label,
  value,
  badge,
}: {
  label: string
  value: string
  badge?: React.ReactNode
}) {
  return (
    <div className="flex items-center justify-between px-4 py-2.5 rounded-lg border border-border bg-background text-sm font-medium">
      <span className="text-muted-foreground">{label}</span>
      <span className="font-mono font-semibold text-foreground mx-2">{value}</span>
      {badge && <span>{badge}</span>}
    </div>
  )
}

function TopBox({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between px-4 py-2.5 rounded-lg border border-secondary bg-secondary text-sm font-medium">
      <span className="text-primary font-semibold">{label}</span>
      <span className="font-mono font-semibold text-primary">{value}</span>
    </div>
  )
}

function Connector({ text, highlight }: { text: string; highlight?: 'red' | 'default' }) {
  return (
    <div className="border-l-2 border-border ml-3 pl-4 py-1">
      <span
        className="text-xs"
        style={{ color: highlight === 'red' ? 'var(--destructive)' : 'var(--muted-foreground)' }}
      >
        {text}
      </span>
    </div>
  )
}

export default function FormulaCascade({ input, result }: Props) {
  const { availability, performance, quality } = result
  const availColor = oeeColorVar(availability, OEE_THRESHOLDS.availability)
  const perfColor  = oeeColorVar(performance,  OEE_THRESHOLDS.performance)
  const qualColor  = oeeColorVar(quality,      OEE_THRESHOLDS.quality)
  const oeeCol     = oeeColorVar(result.oee,   OEE_THRESHOLDS.oee)

  const taktSec = input.idealCycleTimeSec ?? input.optimumTaktTimeSec

  return (
    <div className="space-y-0">
      {/* Row 1 */}
      <TopBox
        label="Gesamtverfügbare Zeit"
        value={formatMinutesAsHours(input.allTimeAvailableMin)}
      />

      {/* Connector: break */}
      {input.plannedBreakMin > 0 && (
        <Connector text={`− Pausen: ${formatMinutesAsHours(input.plannedBreakMin)}`} />
      )}

      {/* Row 2 */}
      <CascadeBox
        label="Betriebszeit"
        value={formatMinutesAsHours(result.totalOperationsTimeMin)}
      />

      {/* Connector: planned downtime */}
      {input.plannedDowntimeMin > 0 && (
        <Connector
          text={`− Geplante Stillstände: ${formatMinutesAsHours(input.plannedDowntimeMin)}`}
        />
      )}

      {/* Row 3 */}
      <CascadeBox
        label="Geplante Produktionszeit"
        value={formatMinutesAsHours(result.potentialProductionTimeMin)}
      />

      {/* Connector: unplanned losses */}
      {result.unplannedLossMin > 0 && (
        <Connector
          text={`− Ungeplante Verluste: ${formatMinutesAsHours(result.unplannedLossMin)}`}
          highlight="red"
        />
      )}

      {/* Row 4 with availability badge */}
      <CascadeBox
        label="Tatsächl. Produktionszeit"
        value={formatMinutesAsHours(result.actualProductionTimeMin)}
        badge={
          <Badge
            value={formatPercent(availability)}
            color={availColor}
            tooltipLabel="Verfügbarkeit (Availability)"
            tooltipFormula="Verfügbarkeit = Tatsächl. Produktionszeit / Geplante Produktionszeit"
            tooltipExample={`${formatMinutesAsHours(result.actualProductionTimeMin)} / ${formatMinutesAsHours(result.potentialProductionTimeMin)} = ${formatPercent(availability)}`}
          />
        }
      />

      {/* Connector: theoretical output */}
      {taktSec && taktSec > 0 && (
        <Connector
          text={`× Taktzeit → Theor. Ausbringung: ${Math.round(result.theoreticalOutput)} Stk.`}
        />
      )}

      {/* Row 5 with performance badge */}
      <CascadeBox
        label="Produzierte Menge"
        value={`${input.producedOutput.toLocaleString('de-DE')} Stk.`}
        badge={
          <Badge
            value={formatPercent(performance)}
            color={perfColor}
            tooltipLabel="Leistungsgrad (Performance)"
            tooltipFormula="Leistung = Ist-Ausbringung / Theor. Ausbringung"
            tooltipExample={`${input.producedOutput.toLocaleString('de-DE')} Stk. / ${Math.round(result.theoreticalOutput).toLocaleString('de-DE')} Stk. = ${formatPercent(performance)}`}
          />
        }
      />

      {/* Connector: good output */}
      <Connector text="Gutmenge:" />

      {/* Row 6 with quality badge */}
      <CascadeBox
        label="Gutmenge"
        value={`${input.goodOutput.toLocaleString('de-DE')} Stk.`}
        badge={
          <Badge
            value={formatPercent(quality)}
            color={qualColor}
            tooltipLabel="Qualitätsrate (Quality)"
            tooltipFormula="Qualität = Gutteile / Gesamtproduktion"
            tooltipExample={`${input.goodOutput.toLocaleString('de-DE')} Stk. / ${input.producedOutput.toLocaleString('de-DE')} Stk. = ${formatPercent(quality)}`}
          />
        }
      />

      {/* Bottom result bar */}
      <div className="bg-primary-dark text-white rounded-xl px-4 py-3 flex items-center justify-between mt-2">
        <FormulaTooltip
          label="OEE — Overall Equipment Effectiveness"
          formula="OEE = Verfügbarkeit × Leistung × Qualität"
          example={`${formatPercent(availability)} × ${formatPercent(performance)} × ${formatPercent(quality)} = ${formatPercent(result.oee)}`}
        >
          <span className="text-xs font-medium opacity-80">
            OEE = {formatPercent(availability)} × {formatPercent(performance)} × {formatPercent(quality)}
          </span>
        </FormulaTooltip>
        <span className="font-mono font-bold text-lg" style={{ color: oeeCol }}>
          {formatPercent(result.oee)}
        </span>
      </div>
    </div>
  )
}
