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

import { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import {
  finalizeAnalysis,
  loadMeasurements,
} from '@/app/oee/analyse/actions'
import {
  aggregateAnalysisKpis,
  aggregateLossBreakdown,
  calculateStationKpis,
  formatPercent,
  type OeeMeasurement,
} from '@/lib/oee/measurement-engine'
import { oeeColorClass } from '@/lib/oee/colors'
import type { OeeStation } from '@/lib/oee/analysis'

type Props = {
  analysisId: string
  stations: OeeStation[]
  status: string
  onPrev: () => void
  onFinalized: () => void
}

export default function AnalysisSummary({
  analysisId,
  stations,
  status,
  onPrev,
  onFinalized,
}: Props) {
  const router = useRouter()
  const [measurements, setMeasurements] = useState<OeeMeasurement[]>([])
  const [submitting, setSubmitting] = useState(false)
  const [errorMsg, setErrorMsg] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      const result = await loadMeasurements(analysisId)
      if (cancelled) return
      if (result.ok && result.data) setMeasurements(result.data)
    })()
    return () => {
      cancelled = true
    }
  }, [analysisId])

  const measurementsByStation = useMemo(() => {
    const map = new Map<string, OeeMeasurement[]>()
    for (const s of stations) map.set(s.id, [])
    for (const m of measurements) {
      const arr = map.get(m.oee_station_id) ?? []
      arr.push(m)
      map.set(m.oee_station_id, arr)
    }
    return map
  }, [stations, measurements])

  const overall = aggregateAnalysisKpis(measurementsByStation)
  const losses = aggregateLossBreakdown(measurements)
  const lossSum = losses.breakdown + losses.setup + losses.microStop + losses.speedLoss + losses.qualityLoss

  const stationsWithKpis = stations.map((s) => ({
    station: s,
    kpis: calculateStationKpis(measurementsByStation.get(s.id) ?? []),
    measurementCount: measurementsByStation.get(s.id)?.length ?? 0,
  }))

  const bottleneck = stationsWithKpis
    .filter((s) => s.measurementCount > 0)
    .reduce<typeof stationsWithKpis[number] | null>((min, cur) => {
      if (!min) return cur
      return cur.kpis.oee < min.kpis.oee ? cur : min
    }, null)

  async function handleFinalize() {
    setSubmitting(true)
    setErrorMsg(null)
    const result = await finalizeAnalysis(analysisId)
    setSubmitting(false)
    if (!result.ok) {
      setErrorMsg(result.error)
      return
    }
    onFinalized()
  }

  return (
    <section className="space-y-5">
      <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
        <BigKpi label="OEE gesamt" value={overall.oee} highlight />
        <BigKpi label="Verfügbarkeit" value={overall.availability} />
        <BigKpi label="Performance" value={overall.performance} />
        <BigKpi label="Qualität" value={overall.quality} />
      </div>

      <div className="bg-card border border-border rounded-md overflow-hidden">
        <header className="px-4 py-3 border-b border-border">
          <h3 className="text-sm font-bold text-foreground">OEE pro Station</h3>
          <p className="text-xs text-muted-foreground">
            {stations.length} Stationen · {measurements.length} Messungen
            {bottleneck && (
              <>
                {' '}
                · Bottleneck:{' '}
                <span className="text-destructive font-bold">{bottleneck.station.name}</span>
              </>
            )}
          </p>
        </header>

        {stations.length === 0 ? (
          <p className="p-4 text-sm text-muted-foreground italic">Keine Stationen.</p>
        ) : (
          <table className="w-full text-xs">
            <thead className="bg-muted/30 text-left">
              <tr>
                <th className="px-3 py-2 font-condensed">Station</th>
                <th className="px-3 py-2 font-condensed text-right">Messungen</th>
                <th className="px-3 py-2 font-condensed text-right">Verfügb.</th>
                <th className="px-3 py-2 font-condensed text-right">Perf.</th>
                <th className="px-3 py-2 font-condensed text-right">Qual.</th>
                <th className="px-3 py-2 font-condensed text-right">OEE</th>
              </tr>
            </thead>
            <tbody>
              {stationsWithKpis.map(({ station, kpis, measurementCount }) => (
                <tr
                  key={station.id}
                  className={`border-t border-border ${bottleneck?.station.id === station.id ? 'bg-destructive/5' : ''}`}
                >
                  <td className="px-3 py-2 font-bold">{station.name}</td>
                  <td className="px-3 py-2 text-right tabular-nums">{measurementCount}</td>
                  <td className="px-3 py-2 text-right tabular-nums">{formatPercent(kpis.availability)}</td>
                  <td className="px-3 py-2 text-right tabular-nums">{formatPercent(kpis.performance)}</td>
                  <td className="px-3 py-2 text-right tabular-nums">{formatPercent(kpis.quality)}</td>
                  <td className={`px-3 py-2 text-right tabular-nums font-bold ${oeeColorClass(kpis.oee)}`}>
                    {formatPercent(kpis.oee)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {lossSum > 0 && (
        <div className="bg-card border border-border rounded-md p-4 space-y-3">
          <h3 className="text-sm font-bold text-foreground">Verlust-Verteilung (Minuten)</h3>
          <LossBar label="Breakdowns" value={losses.breakdown} total={lossSum} colorClass="bg-destructive/70" />
          <LossBar label="Setup & Adjustments" value={losses.setup} total={lossSum} colorClass="bg-warning/70" />
          <LossBar label="Idling & Minor Stops" value={losses.microStop} total={lossSum} colorClass="bg-primary/60" />
          <LossBar label="Reduced Speed" value={losses.speedLoss} total={lossSum} colorClass="bg-muted-foreground/60" />
          <LossBar label="Defects/Quality" value={losses.qualityLoss} total={lossSum} colorClass="bg-destructive/50" />
        </div>
      )}

      {errorMsg && (
        <div role="alert" className="px-3 py-2 bg-destructive/10 border border-destructive/30 text-destructive text-xs rounded-sm">
          {errorMsg}
        </div>
      )}

      <footer className="flex items-center justify-between gap-2 pt-2">
        <button
          type="button"
          onClick={onPrev}
          className="px-3 py-1.5 text-sm font-condensed text-foreground border border-border rounded-sm hover:bg-muted"
        >
          ← Zurück zu Messungen
        </button>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={() => router.push('/oee')}
            className="px-3 py-1.5 text-sm font-condensed text-foreground border border-border rounded-sm hover:bg-muted"
          >
            Speichern und schließen
          </button>
          {status !== 'final' && (
            <button
              type="button"
              onClick={handleFinalize}
              disabled={submitting || measurements.length === 0}
              className="px-3 py-1.5 text-sm font-condensed font-bold text-white bg-primary rounded-sm hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {submitting ? 'Finalisieren…' : 'Analyse finalisieren'}
            </button>
          )}
        </div>
      </footer>
    </section>
  )
}

function BigKpi({ label, value, highlight }: { label: string; value: number; highlight?: boolean }) {
  return (
    <div className={`bg-card border border-border rounded-md p-4 ${highlight ? 'ring-2 ring-primary/20' : ''}`}>
      <div className="text-[10px] font-condensed text-muted-foreground uppercase tracking-wide">{label}</div>
      <div className={`text-3xl font-bold tabular-nums mt-1 ${oeeColorClass(value)}`}>{formatPercent(value)}</div>
    </div>
  )
}

function LossBar({
  label,
  value,
  total,
  colorClass,
}: {
  label: string
  value: number
  total: number
  colorClass: string
}) {
  const pct = total > 0 ? (value / total) * 100 : 0
  return (
    <div className="space-y-1">
      <div className="flex items-center justify-between text-xs">
        <span className="font-condensed">{label}</span>
        <span className="text-muted-foreground tabular-nums">
          {value.toFixed(0)} min · {pct.toFixed(1)}%
        </span>
      </div>
      <div className="h-2 bg-muted/40 rounded-sm overflow-hidden">
        <div className={`h-full ${colorClass}`} style={{ width: `${pct}%` }} />
      </div>
    </div>
  )
}
