'use client'

import React, { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import type { HazardMatchPair, GroundTruthEntry, HazardSummary } from '../_hooks/useBenchmark'

interface Props {
  matched: HazardMatchPair[]
  missing: GroundTruthEntry[]
  extra: HazardSummary[]
}

type TabType = 'matched' | 'missing' | 'extra'

// Per-hazard clarification status fetched once and shared with all detail rows.
type HazardClarStatus = { open: number; answered: number; total: number }

function useClarificationsByHazard(projectId: string | undefined): Record<string, HazardClarStatus> {
  const [byHz, setByHz] = useState<Record<string, HazardClarStatus>>({})
  useEffect(() => {
    if (!projectId) return
    let cancelled = false
    fetch(`/api/sdk/v1/iace/projects/${projectId}/clarifications`)
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (cancelled || !d?.clarifications) return
        const out: Record<string, HazardClarStatus> = {}
        for (const c of d.clarifications as Array<{ affected_hazard_ids: string[]; status: string }>) {
          const isOpen = c.status !== 'answered' && c.status !== 'not_relevant'
          for (const hid of c.affected_hazard_ids) {
            if (!out[hid]) out[hid] = { open: 0, answered: 0, total: 0 }
            out[hid].total += 1
            if (isOpen) out[hid].open += 1
            else out[hid].answered += 1
          }
        }
        setByHz(out)
      })
      .catch(() => {})
    return () => { cancelled = true }
  }, [projectId])
  return byHz
}

export function HazardComparisonTable({ matched, missing, extra }: Props) {
  const [tab, setTab] = useState<TabType>('matched')
  const params = useParams()
  const projectId = params?.projectId as string | undefined
  const clarStatusByHazard = useClarificationsByHazard(projectId)

  // Split matches: >= 50% are real matches, < 50% are weak (shown separately)
  const realMatched = matched.filter(p => p.match_score >= 0.5)
  const weakMatched = matched.filter(p => p.match_score < 0.5)

  // Weak matches: GT entries go to "missing", engine entries go to "extra"
  const allMissing = [...missing, ...weakMatched.map(w => w.gt_entry)]
  const allExtra = [...extra, ...weakMatched.map(w => w.engine_hazard)]

  const greenCount = realMatched.filter(p => p.match_score >= 0.7).length
  const yellowCount = realMatched.filter(p => p.match_score >= 0.5 && p.match_score < 0.7).length

  const tabs: { id: TabType; label: string; count: number; color: string }[] = [
    { id: 'matched', label: `Zugeordnet (${greenCount} exakt, ${yellowCount} aehnlich)`, count: realMatched.length, color: 'text-green-600' },
    { id: 'missing', label: 'Fehlend', count: allMissing.length, color: 'text-red-600' },
    { id: 'extra', label: 'Engine Findings', count: allExtra.length, color: 'text-blue-500' },
  ]

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
      {/* Tab bar */}
      <div className="flex border-b border-gray-200 dark:border-gray-700">
        {tabs.map((t) => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`flex-1 px-4 py-2.5 text-xs font-medium transition-colors ${
              tab === t.id
                ? 'border-b-2 border-purple-600 text-purple-700 dark:text-purple-400'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            {t.label} <span className={t.color}>({t.count})</span>
          </button>
        ))}
      </div>

      <div className="overflow-x-auto">
        {tab === 'matched' && <MatchedTable pairs={realMatched} clarStatusByHazard={clarStatusByHazard} projectId={projectId} />}
        {tab === 'missing' && <MissingTable entries={allMissing} />}
        {tab === 'extra' && <ExtraTable entries={allExtra} clarStatusByHazard={clarStatusByHazard} projectId={projectId} />}
      </div>
    </div>
  )
}

function MatchedTable({ pairs, clarStatusByHazard, projectId }: { pairs: HazardMatchPair[]; clarStatusByHazard: Record<string, HazardClarStatus>; projectId?: string }) {
  const [expanded, setExpanded] = useState<Record<number, boolean>>({})
  if (pairs.length === 0) return <EmptyState text="Keine Zuordnungen gefunden" />
  return (
    <table className="w-full text-xs">
      <thead>
        <tr className="bg-gray-50 dark:bg-gray-700/50">
          <th className="px-3 py-2 text-left font-medium text-gray-500">Nr.</th>
          <th className="px-3 py-2 text-left font-medium text-gray-500">Ground Truth</th>
          <th className="px-3 py-2 text-left font-medium text-gray-500">R</th>
          <th className="px-3 py-2 text-left font-medium text-gray-500">Engine</th>
          <th className="px-3 py-2 text-center font-medium text-gray-500">Score</th>
          <th className="px-3 py-2 text-left font-medium text-gray-500">Qualitaet</th>
        </tr>
      </thead>
      <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
        {pairs.map((p, i) => {
          const quality = p.match_score >= 0.7 ? 'green' : p.match_score >= 0.4 ? 'yellow' : 'red'
          const rowBg = quality === 'green' ? 'bg-green-50/30 dark:bg-green-900/5'
            : quality === 'yellow' ? 'bg-yellow-50/30 dark:bg-yellow-900/5' : ''
          const isOpen = expanded[i]
          return (
            <React.Fragment key={i}>
              <tr className={`hover:bg-gray-50 dark:hover:bg-gray-700/30 cursor-pointer ${rowBg}`}
                onClick={() => setExpanded(prev => ({ ...prev, [i]: !prev[i] }))}>
                <td className="px-3 py-2 text-gray-400">
                  <div className="flex items-center gap-1">
                    <svg className={`w-3 h-3 text-gray-400 transition-transform ${isOpen ? 'rotate-90' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                    </svg>
                    {p.gt_entry.nr}
                  </div>
                </td>
                <td className="px-3 py-2">
                  <div className="font-medium text-gray-800 dark:text-gray-200">{p.gt_entry.hazard_type}</div>
                  <div className="text-gray-400 truncate max-w-[250px]">{p.gt_entry.component_zone}</div>
                </td>
                <td className="px-3 py-2 text-center">
                  <RiskBadge risk={p.gt_entry.risk_in.r} />
                </td>
                <td className="px-3 py-2">
                  <div className="font-medium text-gray-800 dark:text-gray-200">{p.engine_hazard.name}</div>
                  <div className="text-gray-400">{p.engine_hazard.category}</div>
                </td>
                <td className="px-3 py-2 text-center"><ScoreBadge score={p.match_score} /></td>
                <td className="px-3 py-2"><QualityBadge quality={quality} /></td>
              </tr>
              {isOpen && (
                <tr className="bg-gray-50/70 dark:bg-gray-850">
                  <td colSpan={6} className="px-4 py-3">
                    <DetailComparison
                      gt={p.gt_entry}
                      engine={p.engine_hazard}
                      clarStatus={clarStatusByHazard[p.engine_hazard.id]}
                      projectId={projectId}
                    />
                  </td>
                </tr>
              )}
            </React.Fragment>
          )
        })}
      </tbody>
    </table>
  )
}

const LIFECYCLE_LABELS: Record<string, string> = {
  startup: 'Hochfahren', homing: 'Referenzfahrt', automatic_operation: 'Automatikbetrieb',
  manual_operation: 'Handbetrieb', teach_mode: 'Einrichtbetrieb', maintenance: 'Wartung',
  cleaning: 'Reinigung', emergency_stop: 'Not-Halt', recovery_mode: 'Wiederanlauf',
  normal_operation: 'Automatikbetrieb', setup: 'Einrichten', changeover: 'Umruesten',
  fault_clearing: 'Fehlersuche/Stoerungsbeseitigung', commissioning: 'Inbetriebnahme',
  decommissioning: 'Demontage/Ausserbetriebnahme', transport: 'Transport',
  assembly: 'Montage/Installation', inspection: 'Inspektion/Pruefung',
}

function formatLifecycles(raw: string): string {
  if (!raw) return '-'
  return raw.split(',').map(s => s.trim()).map(s => LIFECYCLE_LABELS[s] || s).join(', ')
}

function Chevron({ open }: { open: boolean }) {
  return (
    <svg className={`w-3 h-3 text-gray-400 transition-transform ${open ? 'rotate-90' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
    </svg>
  )
}

/** Ground Truth (professional) detail block — reused by matched + missing rows. */
function GTDetailBlock({ gt }: { gt: GroundTruthEntry }) {
  return (
    <div className="space-y-2">
      <div className="font-semibold text-red-700 dark:text-red-400 uppercase text-[10px]">Ground Truth (Fachmann)</div>
      <DetailRow label="Gefaehrdung" gt={gt.hazard_type} />
      <DetailRow label="Ursache" gt={gt.hazard_cause} />
      <DetailRow label="Gefahrenstelle" gt={gt.component_zone} />
      <DetailRow label="Lebensphasen" gt={gt.lifecycle_phases?.join(', ') || '-'} />
      <DetailRow label="Risiko" gt={`F=${gt.risk_in.f} W=${gt.risk_in.w} P=${gt.risk_in.p} S=${gt.risk_in.s} => R=${gt.risk_in.r}`} />
      {gt.risk_out.r > 0 && (
        <DetailRow label="Restrisiko" gt={`F=${gt.risk_out.f} W=${gt.risk_out.w} P=${gt.risk_out.p} S=${gt.risk_out.s} => R=${gt.risk_out.r}`} />
      )}
      <DetailRow label="Massnahmen" gt={gt.measures?.join('\n') || '-'} multiline />
      <DetailRow label="Typ" gt={gt.measure_type || '-'} />
      {gt.norm_references?.length > 0 && (
        <DetailRow label="Normen" gt={gt.norm_references.join(', ')} />
      )}
      <DetailRow label="Hinreichend" gt={gt.sufficient ? 'JA' : 'NEIN'} />
      {gt.comment && <DetailRow label="Kommentar" gt={gt.comment} />}
    </div>
  )
}

/** Engine (automatic) detail block — reused by matched + extra rows. */
function EngineDetailBlock({ engine, clarStatus, projectId }: {
  engine: HazardSummary; clarStatus?: HazardClarStatus; projectId?: string
}) {
  return (
    <div className="space-y-2">
      <div className="font-semibold text-purple-700 dark:text-purple-400 uppercase text-[10px]">Engine (automatisch)</div>
      <DetailRow label="Gefaehrdung" gt={engine.name} />
      <DetailRow label="Szenario" gt={engine.scenario || extractScenario(engine.description) || '-'} />
      <DetailRow label="Gefahrenstelle" gt={engine.zone || '-'} />
      {engine.lifecycle_phase && (
        <DetailRow label="Lebensphasen" gt={formatLifecycles(engine.lifecycle_phase)} />
      )}
      <DetailRow label="Moeglicher Schaden" gt={engine.possible_harm || '-'} />
      <DetailRow label="Trigger" gt={engine.trigger_event || '-'} />
      {engine.affected_person && (
        <DetailRow label="Betroffene Personen" gt={engine.affected_person} />
      )}
      {engine.mitigations && engine.mitigations.length > 0 ? (
        <DetailRow label="Massnahmen" gt={engine.mitigations.join('\n')} multiline />
      ) : (
        <DetailRow label="Massnahmen" gt="(keine zugeordnet)" />
      )}
      {clarStatus && clarStatus.total > 0 && (
        <ClarificationBanner status={clarStatus} projectId={projectId} />
      )}
      {(() => {
        const norms = extractEngineNorms(engine.description)
        if (norms.length === 0) return null
        return <DetailRow label="Referenzierte Normen" gt={norms.join(' | ')} />
      })()}
    </div>
  )
}

/** Side-by-side detail comparison of GT entry vs. Engine hazard */
function DetailComparison({ gt, engine, clarStatus, projectId }: {
  gt: GroundTruthEntry
  engine: HazardSummary
  clarStatus?: HazardClarStatus
  projectId?: string
}) {
  return (
    <div className="grid grid-cols-2 gap-4 text-xs">
      <GTDetailBlock gt={gt} />
      <EngineDetailBlock engine={engine} clarStatus={clarStatus} projectId={projectId} />
    </div>
  )
}

/**
 * The Go init handler appends two annotated blocks to Hazard.Description:
 *   "<scenario>\n\nMit Anlagenbauer zu klaeren:\n- frage 1\n- frage 2\n\n
 *    Referenzierte Normen: EN 60204-1 Ziff. 6.2 | EN 61140"
 * These helpers split that string back into structured pieces so the UI
 * can render scenario, clarifications and norms as separate sections.
 */
function extractScenario(desc?: string): string {
  if (!desc) return ''
  const idx = desc.indexOf('\n\nMit Anlagenbauer zu klaeren')
  const cut = idx >= 0 ? desc.slice(0, idx) : desc
  // Also cut off a trailing norm line if it's the only suffix
  const normIdx = cut.indexOf('\n\nReferenzierte Normen')
  return (normIdx >= 0 ? cut.slice(0, normIdx) : cut).trim()
}

// (extractClarifications removed in Phase 2 — clarifications are loaded
// from the dedicated /clarifications API and rendered as a status banner
// instead of being parsed out of the hazard description.)

function ClarificationBanner({ status, projectId }: { status: HazardClarStatus; projectId?: string }) {
  const allDone = status.open === 0
  const href = projectId ? `/sdk/iace/${projectId}/clarifications` : '#'
  return (
    <div>
      <div className="text-[10px] font-medium text-gray-500 uppercase">Klärungen</div>
      <a
        href={href}
        className={`mt-0.5 inline-flex items-center gap-2 px-3 py-1.5 rounded border text-xs ${
          allDone
            ? 'bg-green-50 border-green-200 text-green-800 hover:bg-green-100'
            : 'bg-orange-50 border-orange-200 text-orange-800 hover:bg-orange-100'
        }`}
      >
        {allDone ? (
          <>
            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
            Alle {status.total} Klärungen beantwortet
          </>
        ) : (
          <>
            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
            {status.open} offene Klärung{status.open === 1 ? '' : 'en'} {status.answered > 0 && `(${status.answered} beantwortet)`} — Klärungen-Seite öffnen
          </>
        )}
      </a>
    </div>
  )
}

function extractEngineNorms(desc?: string): string[] {
  if (!desc) return []
  const m = desc.match(/Referenzierte Normen:\s*([^\n]+)/)
  if (!m) return []
  return m[1].split('|').map(s => s.trim()).filter(Boolean)
}

function DetailRow({ label, gt, multiline }: { label: string; gt: string; multiline?: boolean }) {
  return (
    <div>
      <div className="text-[10px] font-medium text-gray-500 uppercase">{label}</div>
      {multiline ? (
        <pre className="text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap font-sans mt-0.5">{gt}</pre>
      ) : (
        <div className="text-xs text-gray-700 dark:text-gray-300 mt-0.5">{gt}</div>
      )}
    </div>
  )
}

function MissingTable({ entries }: { entries: GroundTruthEntry[] }) {
  const [expanded, setExpanded] = useState<Record<number, boolean>>({})
  if (entries.length === 0) return <EmptyState text="Keine fehlenden Gefaehrdungen" />
  return (
    <table className="w-full text-xs">
      <thead>
        <tr className="bg-red-50 dark:bg-red-900/20">
          <th className="px-3 py-2 text-left font-medium text-red-600">Nr.</th>
          <th className="px-3 py-2 text-left font-medium text-red-600">Gefaehrdung</th>
          <th className="px-3 py-2 text-left font-medium text-red-600">Ursache</th>
          <th className="px-3 py-2 text-left font-medium text-red-600">Zone</th>
          <th className="px-3 py-2 text-center font-medium text-red-600">R</th>
          <th className="px-3 py-2 text-left font-medium text-red-600">Typ</th>
        </tr>
      </thead>
      <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
        {entries.map((e, i) => {
          const isOpen = expanded[i]
          return (
            <React.Fragment key={i}>
              <tr className="hover:bg-red-50/50 cursor-pointer" onClick={() => setExpanded(p => ({ ...p, [i]: !p[i] }))}>
                <td className="px-3 py-2 text-gray-400">
                  <div className="flex items-center gap-1"><Chevron open={isOpen} />{e.nr}</div>
                </td>
                <td className="px-3 py-2 font-medium text-gray-800 dark:text-gray-200">{e.hazard_type}</td>
                <td className="px-3 py-2 text-gray-600 truncate max-w-[200px]">{e.hazard_cause}</td>
                <td className="px-3 py-2 text-gray-500">{e.component_zone}</td>
                <td className="px-3 py-2 text-center"><RiskBadge risk={e.risk_in.r} /></td>
                <td className="px-3 py-2 text-gray-500">{e.measure_type}</td>
              </tr>
              {isOpen && (
                <tr className="bg-gray-50/70 dark:bg-gray-850">
                  <td colSpan={6} className="px-4 py-3"><GTDetailBlock gt={e} /></td>
                </tr>
              )}
            </React.Fragment>
          )
        })}
      </tbody>
    </table>
  )
}

function ExtraTable({ entries, clarStatusByHazard, projectId }: {
  entries: HazardSummary[]; clarStatusByHazard: Record<string, HazardClarStatus>; projectId?: string
}) {
  const [expanded, setExpanded] = useState<Record<number, boolean>>({})
  if (entries.length === 0) return <EmptyState text="Keine zusaetzlichen Engine-Gefaehrdungen" />
  return (
    <table className="w-full text-xs">
      <thead>
        <tr className="bg-gray-50 dark:bg-gray-700/50">
          <th className="px-3 py-2 text-left font-medium text-gray-500">Name</th>
          <th className="px-3 py-2 text-left font-medium text-gray-500">Kategorie</th>
          <th className="px-3 py-2 text-left font-medium text-gray-500">Zone</th>
        </tr>
      </thead>
      <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
        {entries.map((e, i) => {
          const isOpen = expanded[i]
          return (
            <React.Fragment key={i}>
              <tr className="hover:bg-gray-50 dark:hover:bg-gray-700/30 cursor-pointer" onClick={() => setExpanded(p => ({ ...p, [i]: !p[i] }))}>
                <td className="px-3 py-2 text-gray-800 dark:text-gray-200">
                  <div className="flex items-center gap-1"><Chevron open={isOpen} />{e.name}</div>
                </td>
                <td className="px-3 py-2 text-gray-500">{e.category}</td>
                <td className="px-3 py-2 text-gray-400">{e.zone || '-'}</td>
              </tr>
              {isOpen && (
                <tr className="bg-gray-50/70 dark:bg-gray-850">
                  <td colSpan={3} className="px-4 py-3">
                    <EngineDetailBlock engine={e} clarStatus={clarStatusByHazard[e.id]} projectId={projectId} />
                  </td>
                </tr>
              )}
            </React.Fragment>
          )
        })}
      </tbody>
    </table>
  )
}

function RiskBadge({ risk }: { risk: number }) {
  const color = risk >= 30 ? 'bg-red-100 text-red-700' : risk >= 15 ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700'
  return <span className={`inline-block px-1.5 py-0.5 rounded text-[10px] font-bold ${color}`}>{risk}</span>
}

function ScoreBadge({ score }: { score: number }) {
  const pct = Math.round(score * 100)
  const color = pct >= 70 ? 'text-green-600' : pct >= 50 ? 'text-yellow-600' : 'text-red-600'
  return <span className={`font-bold ${color}`}>{pct}%</span>
}

function QualityBadge({ quality }: { quality: 'green' | 'yellow' | 'red' }) {
  const styles = {
    green: 'bg-green-100 text-green-700 border-green-200',
    yellow: 'bg-yellow-100 text-yellow-700 border-yellow-200',
    red: 'bg-red-100 text-red-700 border-red-200',
  }
  const labels = { green: 'Exakt', yellow: 'Aehnlich', red: 'Schwach' }
  return (
    <span className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${styles[quality]}`}>
      {labels[quality]}
    </span>
  )
}

function EmptyState({ text }: { text: string }) {
  return <div className="px-4 py-8 text-center text-sm text-gray-400">{text}</div>
}
