'use client'

import { CRADemo, CRAFinding, Measure } from '../_hooks/useCRADemo'
import { RISK_BADGE, RISK_LABEL } from './cra-badges'

const TOTAL_ANNEX_I = 40 // CRA Annex I — Anzahl grundlegender Anforderungen
const EFFORT_LABEL: Record<string, string> = {
  code: 'Entwicklung (Code)', hybrid: 'Entwicklung + Prozess',
  process: 'Prozess / Organisation', document: 'Dokumentation',
}

function measureNames(ids: string[], byId: Record<string, Measure>): string[] {
  return ids.map((m) => byId[m]?.name || m)
}

// Top-Risiken in Klartext: zuerst die Cyber-trifft-Safety-Fälle (höchste Wirkung),
// danach mit den höchstpriorisierten Einzelbefunden auffüllen.
function topRisks(data: CRADemo, byId: Record<string, Measure>) {
  const fById: Record<string, CRAFinding> = Object.fromEntries(data.findings.map((f) => [f.id, f]))
  const risks: { title: string; impact: string; systems: string[]; measures: string[]; level: string }[] = []
  for (const cl of data.cross_links) {
    const fs = cl.cyber_finding_ids.map((id) => fById[id]).filter(Boolean)
    risks.push({
      title: cl.safety_hazard,
      impact: cl.cyber_breaks_it,
      systems: Array.from(new Set(fs.map((f) => f.location).filter(Boolean))),
      measures: measureNames(Array.from(new Set(fs.flatMap((f) => f.measures))), byId),
      level: 'CRITICAL',
    })
  }
  const usedIds = new Set(data.cross_links.flatMap((c) => c.cyber_finding_ids))
  const rest = data.findings
    .filter((f) => !usedIds.has(f.id) && (f.priority_tier === 'P0' || f.priority_tier === 'P1'))
    .sort((a, b) => (b.priority_score || 0) - (a.priority_score || 0))
  for (const f of rest) {
    if (risks.length >= 4) break
    risks.push({
      title: f.requirement_title || f.title,
      impact: f.title,
      systems: f.location ? [f.location] : [],
      measures: measureNames(f.measures, byId),
      level: f.risk_level,
    })
  }
  return risks.slice(0, 4)
}

export function ManagementSummary({ data, measuresById }: { data: CRADemo; measuresById: Record<string, Measure> }) {
  const readiness = Math.round(
    (100 * Math.max(0, TOTAL_ANNEX_I - data.requirements_touched.length)) / TOTAL_ANNEX_I,
  )
  const effort: Record<string, number> = {}
  for (const f of data.findings) {
    const k = f.evidence_type || 'process'
    effort[k] = (effort[k] || 0) + 1
  }
  const regulations = Array.from(new Set([
    'Cyber Resilience Act (CRA)',
    'Maschinenverordnung (EU) 2023/1230',
    ...data.findings.flatMap((f) => (f.regulatory_breadth || []).map((c) => c.source_regulation)),
  ].filter(Boolean))).slice(0, 6)
  const risks = topRisks(data, measuresById)

  return (
    <section className="space-y-5">
      <div className="grid gap-4 md:grid-cols-4">
        {/* Readiness */}
        <div className="rounded-xl border border-purple-200 dark:border-purple-800 bg-purple-50/60 dark:bg-purple-900/20 p-5">
          <p className="text-sm text-gray-600 dark:text-gray-300">CRA-Readiness</p>
          <p className="text-4xl font-bold text-purple-700 dark:text-purple-300 mt-1">{readiness}%</p>
          <p className="text-xs text-gray-500 mt-1">
            Anteil der {TOTAL_ANNEX_I} CRA-Anforderungen ohne offenen Befund (indikativ)
          </p>
        </div>
        {/* Offene Risiken */}
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5">
          <p className="text-sm text-gray-600 dark:text-gray-300 mb-2">Offene Risiken</p>
          <div className="space-y-1.5">
            {(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'] as const).map((lvl) =>
              data.by_risk[lvl] ? (
                <div key={lvl} className="flex items-center gap-2">
                  <span className={`inline-flex w-8 justify-center rounded px-2 py-0.5 text-sm font-bold ${RISK_BADGE[lvl]}`}>
                    {data.by_risk[lvl]}
                  </span>
                  <span className="text-sm text-gray-700 dark:text-gray-200">{RISK_LABEL[lvl]}</span>
                </div>
              ) : null,
            )}
          </div>
        </div>
        {/* Handlungsaufwand */}
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5">
          <p className="text-sm text-gray-600 dark:text-gray-300 mb-2">Handlungsaufwand</p>
          <p className="text-3xl font-bold text-gray-900 dark:text-gray-100">{data.findings.length}</p>
          <p className="text-xs text-gray-500 mb-2">offene Befunde</p>
          <ul className="space-y-1">
            {Object.entries(effort).map(([k, n]) => (
              <li key={k} className="text-sm text-gray-700 dark:text-gray-200">
                {n}× {EFFORT_LABEL[k] || k}
              </li>
            ))}
          </ul>
        </div>
        {/* Betroffene Vorschriften */}
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5">
          <p className="text-sm text-gray-600 dark:text-gray-300 mb-2">Betroffene Vorschriften</p>
          <ul className="space-y-1.5">
            {regulations.map((r) => (
              <li key={r} className="text-sm text-gray-700 dark:text-gray-200 flex items-start gap-1.5">
                <span className="text-purple-500 mt-0.5">•</span>{r}
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Top-Risiken in Klartext */}
      <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5">
        <h3 className="text-base font-semibold text-gray-900 dark:text-gray-100 mb-3">Wichtigste Risiken</h3>
        <div className="grid gap-3 md:grid-cols-2">
          {risks.map((r, i) => (
            <div key={i} className="rounded-lg border border-gray-100 dark:border-gray-700/60 p-4">
              <div className="flex items-center gap-2 mb-1">
                <span className={`inline-block rounded px-2 py-0.5 text-xs font-semibold ${RISK_BADGE[r.level] || RISK_BADGE.LOW}`}>
                  {RISK_LABEL[r.level] || r.level}
                </span>
                <span className="text-base font-medium text-gray-900 dark:text-gray-100">{r.title}</span>
              </div>
              <p className="text-sm text-gray-600 dark:text-gray-300 mb-2">{r.impact}</p>
              {r.systems.length > 0 && (
                <p className="text-sm text-gray-500 mb-1">
                  <span className="font-medium text-gray-600 dark:text-gray-300">Betroffene Systeme:</span> {r.systems.join(', ')}
                </p>
              )}
              {r.measures.length > 0 && (
                <p className="text-sm text-gray-500">
                  <span className="font-medium text-gray-600 dark:text-gray-300">Empfohlene Maßnahmen:</span> {r.measures.join(' · ')}
                </p>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* CRA-Fristen */}
      <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5">
        <h3 className="text-base font-semibold text-gray-900 dark:text-gray-100 mb-2">CRA-Fristen</h3>
        <ul className="flex flex-wrap gap-x-6 gap-y-2">
          {data.deadlines.map((d) => (
            <li key={d.date} className="text-sm text-gray-700 dark:text-gray-200 flex items-center gap-2">
              <span className="font-mono font-medium text-purple-600 dark:text-purple-400">{d.date}</span> {d.label}
            </li>
          ))}
        </ul>
      </div>
    </section>
  )
}
