// tdd-guard:skip — React component; pure logic tested via lib/lsc/__tests__/before-after.test.ts
'use client'

import {
  computeBeforeAfterRows,
  computeTotals,
  type BeforeAfterInput,
} from '@/lib/lsc/before-after'
import { isFormulaValue } from '@/lib/lsc/workshop-import'

interface Props {
  inputs: BeforeAfterInput[]
  stationLabel?: string
}

function fmt(n: number | null | undefined, decimals = 1): string {
  if (n == null) return '—'
  return n.toFixed(decimals)
}

function fmtDelta(n: number | null): string {
  if (n == null) return '—'
  const sign = n > 0 ? '+' : ''
  return `${sign}${n.toFixed(1)}`
}

function fmtPct(n: number | null): string {
  if (n == null) return '—'
  const sign = n > 0 ? '+' : ''
  return `${sign}${n.toFixed(1)} %`
}

/** Escape CSV field: wrap in quotes if it contains comma, quote, or newline. */
function escapeCsvField(value: string): string {
  // Guard against formula injection in CSV export
  const sanitized = isFormulaValue(value) ? "'" + value : value
  if (sanitized.includes(',') || sanitized.includes('"') || sanitized.includes('\n')) {
    return `"${sanitized.replace(/"/g, '""')}"`
  }
  return sanitized
}

function buildCsv(inputs: BeforeAfterInput[]): string {
  const rows = computeBeforeAfterRows(inputs)
  const totals = computeTotals(rows)

  const header = [
    'Nr.',
    'Station',
    'Beobachtete CT (s)',
    'Mögliche CT (s)',
    'Delta (s)',
    'Delta (%)',
    'Einsparung',
  ].map(escapeCsvField)

  const dataRows = rows.map((r) =>
    [
      String(r.stepNumber),
      r.stationName,
      fmt(r.observed_ct_sec),
      fmt(r.possible_ct_sec),
      fmtDelta(r.delta_sec),
      fmtPct(r.delta_pct),
      r.hasSaving ? 'Ja' : 'Nein',
    ].map(escapeCsvField),
  )

  const sumRow = [
    '',
    'Gesamt',
    fmt(totals.totalObserved),
    fmt(totals.totalPossible),
    fmtDelta(totals.totalDelta),
    fmtPct(totals.totalDeltaPct),
    '',
  ].map(escapeCsvField)

  const allRows = [header, ...dataRows, sumRow]
  return allRows.map((r) => r.join(',')).join('\n')
}

function downloadCsv(csv: string, filename: string): void {
  const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}

export default function WorkshopBeforeAfterTable({ inputs, stationLabel }: Props) {
  const rows = computeBeforeAfterRows(inputs)
  const totals = computeTotals(rows)
  const hasAnyPossible = rows.some((r) => r.possible_ct_sec != null)

  if (!hasAnyPossible) {
    return (
      <div className="bg-card border border-border rounded-md p-6 text-center">
        <p className="text-sm text-muted-foreground">
          Noch keine Optimierungswerte erfasst
        </p>
      </div>
    )
  }

  const label = stationLabel ?? 'Vorher / Nachher Vergleich'

  return (
    <div className="bg-card border border-border rounded-md overflow-hidden">
      <header className="bg-muted px-4 py-2 flex items-center justify-between">
        <h3 className="text-sm font-bold text-foreground">{label}</h3>
        <button
          type="button"
          onClick={() =>
            downloadCsv(
              buildCsv(inputs),
              `vorher-nachher-${new Date().toISOString().slice(0, 10)}.csv`,
            )
          }
          className="text-xs text-muted-foreground hover:text-primary px-2 py-1 border border-border rounded-sm"
        >
          CSV exportieren
        </button>
      </header>

      <div className="overflow-x-auto">
        <table className="w-full text-xs border-collapse">
          <thead>
            <tr className="border-b border-border bg-background">
              <th className="text-left px-3 py-2 font-semibold text-muted-foreground w-8">
                Nr.
              </th>
              <th className="text-left px-3 py-2 font-semibold text-muted-foreground">
                Station
              </th>
              <th className="text-right px-3 py-2 font-semibold text-muted-foreground">
                Beobachtete CT (s)
              </th>
              <th className="text-right px-3 py-2 font-semibold text-muted-foreground">
                Mögliche CT (s)
              </th>
              <th className="text-right px-3 py-2 font-semibold text-muted-foreground">
                Delta (s)
              </th>
              <th className="text-right px-3 py-2 font-semibold text-muted-foreground">
                Delta (%)
              </th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row) => (
              <tr
                key={row.stepId}
                className={`border-b border-border last:border-0 ${
                  row.hasSaving ? 'bg-status-green/20' : ''
                }`}
              >
                <td className="px-3 py-1.5 text-muted-foreground font-condensed">
                  {row.stepNumber}
                </td>
                <td className="px-3 py-1.5 text-foreground font-medium">
                  {row.stationName}
                </td>
                <td className="px-3 py-1.5 text-right font-condensed text-foreground">
                  {fmt(row.observed_ct_sec)}
                </td>
                <td className="px-3 py-1.5 text-right font-condensed text-foreground">
                  {fmt(row.possible_ct_sec)}
                </td>
                <td
                  className={`px-3 py-1.5 text-right font-condensed font-semibold ${
                    row.hasSaving
                      ? 'text-success'
                      : row.delta_sec != null && row.delta_sec > 0
                        ? 'text-destructive'
                        : 'text-muted-foreground'
                  }`}
                >
                  {fmtDelta(row.delta_sec)}
                </td>
                <td
                  className={`px-3 py-1.5 text-right font-condensed font-semibold ${
                    row.hasSaving
                      ? 'text-success'
                      : row.delta_pct != null && row.delta_pct > 0
                        ? 'text-destructive'
                        : 'text-muted-foreground'
                  }`}
                >
                  {fmtPct(row.delta_pct)}
                </td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr className="border-t-2 border-border bg-muted font-semibold">
              <td className="px-3 py-2 text-muted-foreground" />
              <td className="px-3 py-2 text-foreground">Gesamt</td>
              <td className="px-3 py-2 text-right font-condensed text-foreground">
                {fmt(totals.totalObserved)}
              </td>
              <td className="px-3 py-2 text-right font-condensed text-foreground">
                {fmt(totals.totalPossible)}
              </td>
              <td
                className={`px-3 py-2 text-right font-condensed ${
                  totals.totalDelta != null && totals.totalDelta < 0
                    ? 'text-success'
                    : totals.totalDelta != null && totals.totalDelta > 0
                      ? 'text-destructive'
                      : 'text-muted-foreground'
                }`}
              >
                {fmtDelta(totals.totalDelta)}
              </td>
              <td
                className={`px-3 py-2 text-right font-condensed ${
                  totals.totalDeltaPct != null && totals.totalDeltaPct < 0
                    ? 'text-success'
                    : totals.totalDeltaPct != null && totals.totalDeltaPct > 0
                      ? 'text-destructive'
                      : 'text-muted-foreground'
                }`}
              >
                {fmtPct(totals.totalDeltaPct)}
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  )
}
