// Fertigungs-Differenzen als U-08-Tabelle (Loop 3 Schritt 4b).
//
// Zeigt Katalog-Sätze, nicht DB-Zeilen: jede Zeile trägt ihre Difference ID
// und ist damit bis in den Katalog rückverfolgbar. Die Filter-Transparenz
// (ausgeblendete Zeilen samt Delta-Summe) gehört laut U-08 sichtbar an die
// Tabelle — ohne aktiven Filter bleibt sie still. Reine Server-Komponente.

import type { TableSpec } from '@/lib/qaf-differences/internal/table-specs'
import type { DifferenceCell } from '@/lib/qaf-differences/internal/all-differences'
import {
  cellReference,
  fileLabel,
  isWeakState,
  valueStateLabel,
} from '@/components/qaf-differences/qaf-v2-evidence-panel'

const de = new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
const fmt = (v: number | null) => (v === null ? '—' : de.format(v))

/** SRC-002 (Loop 5): eine Beleg-Zelle der Kette — `Blatt!Zelle`, Formel als
 * title (erreichbar ohne Platzverbrauch), abweichender Wertzustand benannt.
 * Die Datei-Ebene trägt die Rolle (Vergabestand/Aktueller Stand) — dieselben
 * Begriffe wie der Seitenkopf. */
function BelegZelle({ cell }: { cell: DifferenceCell }) {
  // Review-Fix #492: Rolle, Zellbezug und Zustands-Vokabular kommen aus dem
  // Evidence-Panel — EIN Vokabular, exhaustive Label-Map (ein sechster
  // ValueState bricht dort den Build statt hier still zu verschwinden).
  // Benannt wird, was den Wert schwächt (isWeakState: Fehlerwert, fremde
  // Datei) — plus „leer", weil eine leere Seite neben einer gefüllten die
  // Aussage der Zeile verändert. Normale Zustände tragen keinen Zusatz.
  const benennen = isWeakState(cell.valueState) || cell.valueState === 'empty'
  return (
    <span
      className="font-mono text-xs"
      title={`${fileLabel(cell.fileRole)}${cell.formula ? ` · Formel: ${cell.formula}` : ''}`}
    >
      {cellReference(cell)}
      {benennen ? (
        <span className="ml-1 font-sans text-muted-foreground">
          ({valueStateLabel(cell.valueState)})
        </span>
      ) : null}
    </span>
  )
}

/** Beide Seiten des Belegs, in Rollen-Reihenfolge (award zuerst). */
function BelegSpalte({ cells }: { cells: DifferenceCell[] }) {
  if (cells.length === 0) return <>—</>
  const sortiert = [...cells].sort((a, b) => (a.fileRole === b.fileRole ? 0 : a.fileRole === 'award' ? -1 : 1))
  return (
    <span className="flex flex-col gap-0.5">
      {sortiert.map((c, i) => (
        <BelegZelle key={`${c.fileRole}-${c.sheet}-${c.cell}-${i}`} cell={c} />
      ))}
    </span>
  )
}

interface Props {
  spec: TableSpec
}

export function QafV2DifferencesTable({ spec }: Props) {
  return (
    <div className="space-y-2">
      <div className="overflow-x-auto rounded-[2px] border border-border">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted text-left text-muted-foreground">
              <th className="px-3 py-2 font-medium">Kennung</th>
              <th className="px-3 py-2 font-medium">Station · Feld</th>
              <th className="px-3 py-2 font-medium">Zuordnung</th>
              <th className="px-3 py-2 text-right font-medium">Vergabestand</th>
              <th className="px-3 py-2 text-right font-medium">Aktueller Stand</th>
              <th className="px-3 py-2 text-right font-medium">Δ</th>
              <th className="px-3 py-2 font-medium">Beleg</th>
            </tr>
          </thead>
          <tbody>
            {spec.rows.map((r) => (
              <tr key={r.differenceId} className="border-b border-border/60 last:border-b-0">
                <td className="px-3 py-1.5 font-mono text-xs">{r.differenceId}</td>
                <td className="px-3 py-1.5">{r.namesAward.join(' · ') || '—'}</td>
                <td className="px-3 py-1.5 text-muted-foreground">{r.matchType}</td>
                <td className="px-3 py-1.5 text-right tabular-nums">{fmt(r.valueAward)}</td>
                <td className="px-3 py-1.5 text-right tabular-nums">{fmt(r.valueCurrent)}</td>
                <td className="px-3 py-1.5 text-right font-medium tabular-nums">{fmt(r.delta)}</td>
                <td className="px-3 py-1.5">
                  <BelegSpalte cells={r.cells} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="text-xs text-muted-foreground">
        {spec.rows.length} von {spec.totalRows} Zeilen · Summe der angezeigten Deltas: {fmt(spec.displayedDeltaSum)}
        {spec.hidden.count > 0
          ? ` · ${spec.hidden.count} Zeile(n) ausgeblendet (Summe ${fmt(spec.hidden.deltaSum)})`
          : null}
      </p>
      {spec.noticeDe !== null ? <p className="text-xs text-muted-foreground">{spec.noticeDe}</p> : null}
    </div>
  )
}
