'use client'

import type { RiskComparisonPair, RiskAgreement } from '../_hooks/useBenchmark'

type Ampel = 'green' | 'yellow' | 'red'

// EN-62061-style risk number R = S * (F + W + P) → traffic light (like the Excel).
function ampelEN(r: number): Ampel {
  if (r >= 30) return 'red'
  if (r >= 18) return 'yellow'
  return 'green'
}

function ampelBand(band: string): Ampel {
  if (band === 'sehr hoch' || band === 'hoch') return 'red'
  if (band === 'wesentlich' || band === 'moeglich') return 'yellow'
  return 'green'
}

// Tool confidence (how well-anchored the estimate is) → chip color.
function ampelConfidence(c: string): Ampel {
  if (c === 'hoch') return 'green'
  if (c === 'mittel') return 'yellow'
  return 'red'
}

const cellColor: Record<Ampel, string> = {
  red: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
  yellow: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/40 dark:text-yellow-300',
  green: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',
}

function pctColor(p: number): Ampel {
  if (p >= 80) return 'green'
  if (p >= 50) return 'yellow'
  return 'red'
}

function Stat({ label, pct }: { label: string; pct: number }) {
  const c = pctColor(pct)
  return (
    <div className={`rounded-lg border-2 p-3 text-center ${c === 'green' ? 'border-green-200 dark:border-green-800' : c === 'yellow' ? 'border-yellow-200 dark:border-yellow-800' : 'border-red-200 dark:border-red-800'}`}>
      <div className={`text-xl font-bold ${c === 'green' ? 'text-green-600' : c === 'yellow' ? 'text-yellow-600' : 'text-red-600'}`}>{Math.round(pct)}%</div>
      <div className="text-[10px] text-gray-500 mt-0.5">{label}</div>
    </div>
  )
}

export function RiskComparison({ pairs, agreement }: { pairs?: RiskComparisonPair[]; agreement?: RiskAgreement }) {
  if (!pairs || pairs.length === 0) return null

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 space-y-4">
      <div>
        <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">Risikozahlen-Vergleich (Fachmann vs. Tool)</h3>
        <p className="text-xs text-gray-500 mt-0.5">
          R = S × (F + W + P), Ampel wie in der Excel. Das Tool nennt einen <strong>Schätzbereich</strong>{' '}
          (nicht einen exakten Punktwert) plus Konfidenz — die endgültige Bewertung trifft der/die Sachverständige.
          Fine-Kinney (P×E×C) als zweite, US-anerkannte Bewertung.
        </p>
      </div>

      {agreement && agreement.n > 0 && (
        <>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
            <Stat label="Schwere S ±1" pct={agreement.severity_within1} />
            <Stat label="Haeufigkeit F ±1" pct={agreement.frequency_within1} />
            <Stat label="Wahrsch. W ±1" pct={agreement.probability_within1} />
            <Stat label="Vermeidb. P ±1" pct={agreement.avoidance_within1} />
            <Stat label="Ranking (FK)" pct={agreement.rank_concordance} />
          </div>
          {typeof agreement.high_confidence_pct === 'number' && (
            <p className="text-xs text-gray-500">
              Tool-Konfidenz: <strong>{Math.round(agreement.high_confidence_pct)}%</strong> der erkannten
              Gefaehrdungen mit hoher Konfidenz (Verletzungsmechanismus eindeutig aus dem Szenario ableitbar).
            </p>
          )}
        </>
      )}

      <div className="overflow-x-auto">
        <table className="w-full text-xs">
          <thead>
            <tr className="text-gray-500 border-b border-gray-200 dark:border-gray-700">
              <th className="text-left py-1.5 px-2">Gefaehrdung</th>
              <th className="px-1 text-center" colSpan={5}>Fachmann · S F W P <strong>R</strong></th>
              <th className="px-1 text-center border-l border-gray-200 dark:border-gray-700" colSpan={4}>Tool · S F W P</th>
              <th className="px-1 text-center border-l border-gray-200 dark:border-gray-700">Risiko (Schätzbereich) / FK</th>
              <th className="px-1 text-center border-l border-gray-200 dark:border-gray-700">Konfidenz</th>
            </tr>
          </thead>
          <tbody>
            {pairs.map((p, i) => (
              <tr key={i} className="border-b border-gray-100 dark:border-gray-700/50">
                <td className="py-1 px-2 text-gray-700 dark:text-gray-300">{p.hazard_name || '—'}</td>
                <td className="text-center text-gray-500">{p.gt_severity}</td>
                <td className="text-center text-gray-500">{p.gt_frequency}</td>
                <td className="text-center text-gray-500">{p.gt_probability}</td>
                <td className="text-center text-gray-500">{p.gt_avoidance}</td>
                <td className={`text-center font-bold rounded ${cellColor[ampelEN(p.gt_risk)]}`}>{p.gt_risk}</td>
                <td className="text-center text-gray-500 border-l border-gray-200 dark:border-gray-700">{p.eng_severity}</td>
                <td className="text-center text-gray-500">{p.eng_frequency}</td>
                <td className="text-center text-gray-500">{p.eng_probability}</td>
                <td className="text-center text-gray-500">{p.eng_avoidance}</td>
                <td className="text-center border-l border-gray-200 dark:border-gray-700 whitespace-nowrap">
                  <span
                    className={`inline-block font-bold rounded px-1.5 ${cellColor[ampelEN(p.eng_risk_point)]}`}
                    title={`Schätzbereich R ${p.eng_risk_low}–${p.eng_risk_high} (${p.eng_risk_level_range})`}
                  >
                    {p.eng_risk_low}–{p.eng_risk_high}
                  </span>
                  <span className="ml-1 text-[10px] text-gray-400">≈{p.eng_risk_point}</span>
                  <span className={`ml-1 inline-block rounded px-1 ${cellColor[ampelBand(p.fk_band)]}`} title={`Fine-Kinney ${p.fk_band}`}>FK&nbsp;{Math.round(p.fk_score)}</span>
                  <div className="text-[9px] text-gray-400 mt-0.5">{p.eng_risk_level_range}</div>
                </td>
                <td className="text-center border-l border-gray-200 dark:border-gray-700">
                  <span className={`inline-block rounded px-1.5 py-0.5 text-[10px] font-medium ${cellColor[ampelConfidence(p.confidence)]}`}>
                    {p.confidence}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
