'use client'

import { Fragment, useState } from 'react'
import { CRADemo, CRAFinding, Measure } from '../_hooks/useCRADemo'
import { EvidenceTag, RiskBadge, TierBadge } from './cra-badges'

function FindingDetail({ f, measuresById }: { f: CRAFinding; measuresById: Record<string, Measure> }) {
  return (
    <td colSpan={5} className="px-4 py-4 space-y-4">
      {/* Best-Practice-Standard — der Maßstab (kein Code-Rezept) */}
      <div>
        <p className="text-sm font-semibold text-gray-700 dark:text-gray-200 mb-1.5">
          Best-Practice-Standard — woran „erfüllt" gemessen wird
        </p>
        <div className="flex flex-wrap gap-1.5 items-center text-sm">
          <span className="text-gray-500">Gesetz:</span>
          <span className="rounded bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300 px-2 py-0.5 font-mono text-xs">
            {f.primary_requirement} · {f.annex_anchor}
          </span>
          <span className="text-gray-500 ml-2">NIST:</span>
          {f.nist_refs.map((n) => (
            <span key={n} className="rounded bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300 px-2 py-0.5 font-mono text-xs">{n}</span>
          ))}
          <span className="text-gray-500 ml-2">OWASP:</span>
          {f.owasp_refs.map((o) => (
            <span key={o.code} className="rounded bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-2 py-0.5 text-xs font-medium">{o.code} · {o.label}</span>
          ))}
          {f.iso27001_ref.length > 0 && (
            <>
              <span className="text-gray-500 ml-2">ISO 27001:</span>
              {f.iso27001_ref.map((iso) => (
                <span key={iso} className="rounded bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-300 px-2 py-0.5 text-xs">{iso}</span>
              ))}
            </>
          )}
        </div>
      </div>

      {/* Maßnahmen (wählbar) — kuratiert + belegte Optionen */}
      <div>
        <p className="text-sm font-semibold text-gray-700 dark:text-gray-200 mb-1.5">
          Maßnahmen (wählbar — passend kombinieren, nicht alle abhaken)
        </p>
        {f.measures.length > 0 && (
          <ul className="space-y-1.5 mb-2">
            {f.measures.map((mid) => {
              const m = measuresById[mid]
              return (
                <li key={mid} className="text-sm text-gray-700 dark:text-gray-200">
                  <span className="font-medium">{m ? m.name : mid}</span>
                  {m?.tier === 'review' && (
                    <span title="KI-vorgeschlagen — mit DSB/Auditor verifizieren" className="ml-1 rounded bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300 px-1 py-0.5 text-[11px]">indikativ</span>
                  )}
                  {m?.description ? <span className="text-gray-500"> — {m.description}</span> : null}
                  {m?.norm_sources?.length ? (
                    <span className="mt-1 flex flex-wrap gap-1">
                      {m.norm_sources.map((s) => (
                        <span key={s.ref} title={s.label}
                          className={`rounded px-1.5 py-0.5 text-[11px] ${
                            s.license_class === 'paid_reference'
                              ? 'bg-amber-50 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'
                              : 'bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300'}`}>
                          {s.ref}{s.license_class === 'paid_reference' ? ' · nur Verweis' : ''}
                        </span>
                      ))}
                    </span>
                  ) : (m?.norm_refs?.length ? <span className="text-gray-400"> · {m.norm_refs.join(', ')}</span> : null)}
                </li>
              )
            })}
          </ul>
        )}
        {f.regulatory_breadth && f.regulatory_breadth.length > 0 && (
          <ul className="space-y-1">
            {f.regulatory_breadth.map((c) => (
              <li key={c.control_id} className="text-sm text-gray-600 dark:text-gray-300">
                <span className="rounded bg-gray-200 text-gray-600 dark:bg-gray-600 dark:text-gray-200 px-1.5 py-0.5 text-xs mr-1.5">{c.use_case || 'Option'}</span>
                {c.title}<span className="text-gray-400"> · {c.source_regulation}</span>
              </li>
            ))}
          </ul>
        )}
      </div>

      <p className="text-sm text-gray-400 italic">
        Befund-Kennung {f.id} · {f.cwe}. Konkreter Code-Fix folgt aus dem Repo-Scan, sobald das Repository angebunden ist.
      </p>
    </td>
  )
}

export function TechFindings({ data, measuresById }: { data: CRADemo; measuresById: Record<string, Measure> }) {
  const [show, setShow] = useState(false)
  const [open, setOpen] = useState<Record<string, boolean>>({})
  const toggle = (id: string) => setOpen((o) => ({ ...o, [id]: !o[id] }))
  const mNames = (ids: string[]) => ids.map((m) => measuresById[m]?.name || m)

  return (
    <section className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
      <button
        onClick={() => setShow((s) => !s)}
        className="w-full flex items-center justify-between px-5 py-4 text-left"
      >
        <span>
          <span className="text-base font-semibold text-gray-900 dark:text-gray-100">
            Technische Details — für Entwickler &amp; Auditoren
          </span>
          <span className="block text-sm text-gray-500 mt-0.5">
            {data.findings.length} Cyber-Befunde mit Standard-Crosswalk &amp; Maßnahmen
          </span>
        </span>
        <span className="text-purple-600 text-sm">{show ? 'ausblenden ▲' : 'anzeigen ▼'}</span>
      </button>

      {show && (
        <div className="px-2 pb-4 overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-gray-500 border-b border-gray-200 dark:border-gray-700 text-left">
                <th className="py-2 px-3">Prio</th>
                <th className="py-2 px-4">Cyber-Befund &amp; Pflicht</th>
                <th className="py-2 px-3">Risiko</th>
                <th className="py-2 px-3">Maßnahmen</th>
                <th className="py-2 px-3 text-right">Details</th>
              </tr>
            </thead>
            <tbody>
              {data.findings.map((f) => (
                <Fragment key={f.id}>
                  <tr className="border-b border-gray-100 dark:border-gray-700/50 align-top">
                    <td className="py-3 px-3"><TierBadge tier={f.priority_tier} reason={f.priority_reason} /></td>
                    <td className="py-3 px-4 max-w-md">
                      <div className="text-gray-900 dark:text-gray-100 font-medium">{f.title}</div>
                      <div className="text-sm text-gray-600 dark:text-gray-300">Pflicht: {f.requirement_title}</div>
                      <div className="mt-1.5"><EvidenceTag et={f.evidence_type} /></div>
                    </td>
                    <td className="py-3 px-3"><RiskBadge level={f.risk_level} /></td>
                    <td className="py-3 px-3 text-gray-700 dark:text-gray-200">
                      {f.measures.length ? mNames(f.measures).join(' · ') : <span className="text-gray-400">—</span>}
                    </td>
                    <td className="py-3 px-3 text-right">
                      <button onClick={() => toggle(f.id)} className="text-sm text-purple-600 hover:underline whitespace-nowrap">
                        {open[f.id] ? 'weniger ▲' : 'Standard & Maßnahmen ▼'}
                      </button>
                    </td>
                  </tr>
                  {open[f.id] && (
                    <tr className="border-b border-gray-100 dark:border-gray-700/50 bg-gray-50/60 dark:bg-gray-900/30">
                      <FindingDetail f={f} measuresById={measuresById} />
                    </tr>
                  )}
                </Fragment>
              ))}
            </tbody>
          </table>

          {data.findings.some((f) => f.quick_win) && (
            <div className="mt-4 mx-3 rounded-lg border border-green-200 dark:border-green-800 bg-green-50/50 dark:bg-green-900/10 p-4">
              <h3 className="text-base font-semibold text-gray-900 dark:text-gray-100">Quick Wins</h3>
              <p className="text-sm text-gray-500 mb-2">Hohe Wirkung bei geringem Aufwand — gut für den Einstieg.</p>
              <ul className="space-y-1.5">
                {data.findings.filter((f) => f.quick_win).map((f) => (
                  <li key={f.id} className="text-sm text-gray-700 dark:text-gray-200 flex items-start gap-2">
                    <TierBadge tier={f.priority_tier} reason={f.priority_reason} />
                    <span>{f.title}
                      {f.measures.length > 0 && <span className="text-gray-500"> · {mNames(f.measures).join(' · ')}</span>}
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </section>
  )
}
