/**
 * ProjectKpiSection — Modul-Kennzahlen für die Projekt-Übersicht (KAR-983).
 *
 * Reine Anzeige-Komponente: keine eigene Datenbeschaffung. Alle Werte kommen
 * bereits berechnet aus lib/reporting/project-kpis.ts (Server Component ruft
 * die Compute-Funktionen auf und reicht das Ergebnis durch). Jede Kachel
 * degradiert sauber zu einer "Keine Daten"-Meldung, wenn die zugehörige
 * Compute-Funktion `null` liefert (kein Assessment / kein Vergleich / kein
 * Wertstrom / keine Maßnahmen).
 */
import * as React from 'react'
import Link from 'next/link'
import { ClipboardList, FileDiff, Workflow, ListChecks, ArrowRight } from 'lucide-react'
import type {
  FactoryAnalysisKpi,
  QafKpiData,
  ValueStreamKpi,
  MeasuresKpi,
} from '@/lib/reporting/project-kpis'

// No DemoBadge here: the sticky ProjectHeader (layout.tsx) already renders it
// for every /project/[id] route — a second badge in this section duplicated it
// on the same screen (PR #347 review fix).
interface Props {
  projectId: string
  factoryAnalysis: FactoryAnalysisKpi | null
  qaf: QafKpiData | null
  valueStream: ValueStreamKpi | null
  /** `/wertstrom/{mapId}` when a map exists, otherwise the safe `/wertstrom` index. */
  valueStreamHref: string
  measures: MeasuresKpi | null
}

function formatSignedPercent(value: number | null): string {
  if (value === null) return '—'
  const sign = value > 0 ? '+' : ''
  return `${sign}${value.toLocaleString('de-DE', { minimumFractionDigits: 1, maximumFractionDigits: 1 })} %`
}

/** Anteil `count` an `total`, gerundet — `—` statt Division durch 0. */
function formatSharePct(count: number, total: number): string {
  if (total === 0) return '—'
  return `${Math.round((count / total) * 100)} %`
}

/** Kostensenkung = positiv (grün), Kostensteigerung = negativ (rot). */
function costDeltaClass(value: number | null): string {
  if (value === null || value === 0) return 'text-foreground'
  return value < 0 ? 'text-success-text' : 'text-destructive'
}

function formatLeadTime(totalSeconds: number): string {
  if (totalSeconds < 60) return `${Math.round(totalSeconds)} s`
  const totalMinutes = Math.round(totalSeconds / 60)
  if (totalMinutes < 60) return `${totalMinutes} min`
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60
  return minutes > 0 ? `${hours} h ${minutes} min` : `${hours} h`
}

function ModuleTile({
  icon,
  title,
  href,
  linkLabel,
  children,
}: {
  icon: React.ReactNode
  title: string
  href: string
  linkLabel: string
  children: React.ReactNode
}) {
  return (
    <div className="bg-card rounded-xl border border-border p-4 flex flex-col gap-2">
      <div className="flex items-center gap-2 text-muted-foreground">
        {icon}
        <h3 className="text-xs font-semibold text-foreground uppercase tracking-wide">{title}</h3>
      </div>
      <div className="flex-1">{children}</div>
      <Link
        href={href}
        className="inline-flex items-center gap-1 text-xs text-primary hover:underline w-fit"
      >
        {linkLabel}
        <ArrowRight size={12} />
      </Link>
    </div>
  )
}

export default function ProjectKpiSection({
  projectId,
  factoryAnalysis,
  qaf,
  valueStream,
  valueStreamHref,
  measures,
}: Props) {
  return (
    <section className="space-y-3">
      <div className="flex items-center gap-2">
        <h2 className="text-sm font-semibold text-foreground">Kennzahlen</h2>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <ModuleTile
          icon={<ClipboardList size={14} />}
          title="Fabrikanalyse"
          href={`/fabrikanalyse/${projectId}`}
          linkLabel={factoryAnalysis ? 'Zur Fabrikanalyse' : 'Fabrikanalyse anlegen'}
        >
          {factoryAnalysis === null ? (
            <p className="text-sm text-muted-foreground">Keine Fabrikanalyse vorhanden</p>
          ) : (
            <>
              <div className="flex items-baseline gap-1.5">
                <span className="text-2xl font-bold tabular-nums text-primary">
                  {factoryAnalysis.scoreAvg !== null ? factoryAnalysis.scoreAvg.toFixed(1) : '—'}
                </span>
                <span className="text-xs text-muted-foreground">/ 4 Erfüllungs-Score</span>
              </div>
              <div className="flex flex-wrap gap-x-3 gap-y-0.5 mt-1.5 text-xs">
                <span className="text-success-text">
                  {formatSharePct(factoryAnalysis.fulfilledCount, factoryAnalysis.answeredCount)} erfüllt
                </span>
                <span className="text-warning">
                  {formatSharePct(factoryAnalysis.partialCount, factoryAnalysis.answeredCount)} teilweise
                </span>
                <span className="text-destructive">
                  {formatSharePct(factoryAnalysis.notFulfilledCount, factoryAnalysis.answeredCount)} nicht erfüllt
                </span>
              </div>
              <p className="text-xs text-muted-foreground mt-1">
                {factoryAnalysis.answeredCount} Frage(n) beantwortet
              </p>
            </>
          )}
        </ModuleTile>

        <ModuleTile
          icon={<FileDiff size={14} />}
          title="QAF-Vergleich"
          href={`/project/${projectId}/qaf`}
          linkLabel="Zum QAF-Vergleich"
        >
          {qaf === null ? (
            <p className="text-sm text-muted-foreground">Keine Daten</p>
          ) : qaf.kpis === null ? (
            <p className="text-sm text-muted-foreground">
              {qaf.comparisonTitle ?? qaf.partNumber ?? 'Neuester Vergleich'} — keine Kernkennzahlen verfügbar
            </p>
          ) : (
            <>
              <div
                className={`text-2xl font-bold tabular-nums ${costDeltaClass(qaf.kpis.totalProductionCosts.deltaPercent)}`}
              >
                {formatSignedPercent(qaf.kpis.totalProductionCosts.deltaPercent)}
              </div>
              <p className="text-xs text-muted-foreground">Summe Herstellkosten Δ</p>
              <div className="flex flex-wrap gap-x-3 gap-y-0.5 mt-1.5 text-xs text-muted-foreground">
                <span>Angebotspreis {formatSignedPercent(qaf.kpis.quotationPrice.deltaPercent)}</span>
                <span>Material {formatSignedPercent(qaf.kpis.materialCosts.deltaPercent)}</span>
              </div>
            </>
          )}
        </ModuleTile>

        <ModuleTile
          icon={<Workflow size={14} />}
          title="Wertstrom"
          href={valueStreamHref}
          linkLabel={valueStream ? 'Zum Wertstrom' : 'Wertstrom anlegen'}
        >
          {valueStream === null ? (
            <p className="text-sm text-muted-foreground">Keine Daten</p>
          ) : (
            <>
              <div className="text-2xl font-bold tabular-nums text-primary">
                {valueStream.leadTimeSec !== null ? formatLeadTime(valueStream.leadTimeSec) : '—'}
              </div>
              <p className="text-xs text-muted-foreground">Durchlaufzeit</p>
              <div className="flex flex-wrap gap-x-3 gap-y-0.5 mt-1.5 text-xs text-muted-foreground">
                <span>VA-Anteil {valueStream.vaRatioPct !== null ? `${valueStream.vaRatioPct} %` : '—'}</span>
                <span>Engpass {valueStream.bottleneckName ?? '—'}</span>
              </div>
            </>
          )}
        </ModuleTile>

        <ModuleTile
          icon={<ListChecks size={14} />}
          title="Maßnahmen"
          href={`/project/${projectId}/workshop`}
          linkLabel="Zu den Maßnahmen"
        >
          {measures === null ? (
            <p className="text-sm text-muted-foreground">Keine Maßnahmen vorhanden</p>
          ) : (
            <>
              <div className="text-2xl font-bold tabular-nums text-primary">{measures.total}</div>
              <p className="text-xs text-muted-foreground">Maßnahmen gesamt</p>
              <div className="flex flex-wrap gap-x-3 gap-y-0.5 mt-1.5 text-xs">
                <span className="text-warning">{measures.open} offen</span>
                <span className="text-muted-foreground">{measures.inProgress} in Arbeit</span>
                <span className="text-success-text">{measures.done} erledigt</span>
              </div>
            </>
          )}
        </ModuleTile>
      </div>
    </section>
  )
}
