'use client'

import React, { useState } from 'react'

interface Props {
  result: {
    vendor_name: string
    documents: DocumentResult[]
    findings: Finding[]
    overall_score: number
    category_scores: Record<string, number>
    cross_check_findings: CrossCheckFinding[]
    report_html: string
    checked_at: string
  }
  onReset: () => void
}

interface DocumentResult {
  label: string
  doc_type: string
  completeness_pct: number
  correctness_pct: number
  checks: Check[]
  findings_count: number
  error: string
}

interface Check {
  id: string
  label: string
  passed: boolean
  severity: string
  level: number
  parent: string | null
  skipped: boolean
  hint: string
}

interface Finding {
  id: string
  category: string
  severity: string
  type: string
  title: string
  description: string
  document_label: string
  document_type: string
}

interface CrossCheckFinding {
  id: string
  label: string
  severity: string
  hint: string
}

const CAT_LABELS: Record<string, string> = {
  INSTRUCTION: 'Weisungsgebundenheit',
  CONFIDENTIALITY: 'Vertraulichkeit',
  TOM: 'TOM (Art. 32)',
  SUBPROCESSOR: 'Unterauftragsverarbeitung',
  DATA_SUBJECT_RIGHTS: 'Betroffenenrechte',
  DELETION: 'Loeschung/Rueckgabe',
  AUDIT_RIGHTS: 'Audit-/Inspektionsrechte',
  INCIDENT: 'Datenschutzverletzungen',
  TRANSFER: 'Drittlandtransfer',
  LIABILITY: 'Haftung',
  AVV_CONTENT: 'AVV Inhalt',
}

const SEV_COLORS: Record<string, string> = {
  CRITICAL: 'bg-red-100 text-red-700 border-red-200',
  HIGH: 'bg-orange-100 text-orange-700 border-orange-200',
  MEDIUM: 'bg-yellow-100 text-yellow-700 border-yellow-200',
  LOW: 'bg-green-100 text-green-700 border-green-200',
}

function scoreColor(s: number) {
  if (s >= 80) return 'text-green-600'
  if (s >= 50) return 'text-yellow-600'
  return 'text-red-600'
}

function scoreBg(s: number) {
  if (s >= 80) return 'bg-green-50 border-green-200'
  if (s >= 50) return 'bg-yellow-50 border-yellow-200'
  return 'bg-red-50 border-red-200'
}

function verdict(s: number) {
  if (s >= 80) return 'Bestanden'
  if (s >= 50) return 'Bedingt bestanden'
  return 'Nicht bestanden'
}

export function PruefprotokollView({ result, onReset }: Props) {
  const [expandedDoc, setExpandedDoc] = useState<number | null>(null)
  const [showHtml, setShowHtml] = useState(false)

  const criticalCount = result.findings.filter(f => f.severity === 'CRITICAL').length
    + result.cross_check_findings.filter(f => f.severity === 'CRITICAL').length
  const totalFindings = result.findings.length + result.cross_check_findings.length

  return (
    <div className="space-y-6">
      {/* Score Overview */}
      <div className={`rounded-xl border-2 p-8 text-center ${scoreBg(result.overall_score)}`}>
        <div className="text-sm text-gray-500 mb-1">Pruefprotokoll — {result.vendor_name}</div>
        <div className={`text-6xl font-extrabold ${scoreColor(result.overall_score)}`}>
          {result.overall_score}%
        </div>
        <div className="text-lg text-gray-600 mt-1">{verdict(result.overall_score)}</div>
      </div>

      {/* Summary Stats */}
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border p-5 text-center">
          <div className="text-3xl font-bold text-gray-900">{result.documents.length}</div>
          <div className="text-xs text-gray-500 mt-1 uppercase tracking-wide">Dokumente</div>
        </div>
        <div className="bg-white rounded-xl border p-5 text-center">
          <div className="text-3xl font-bold text-gray-900">{totalFindings}</div>
          <div className="text-xs text-gray-500 mt-1 uppercase tracking-wide">Findings</div>
        </div>
        <div className="bg-white rounded-xl border p-5 text-center">
          <div className="text-3xl font-bold text-red-600">{criticalCount}</div>
          <div className="text-xs text-gray-500 mt-1 uppercase tracking-wide">Kritisch</div>
        </div>
      </div>

      {/* Category Scores */}
      {Object.keys(result.category_scores).length > 0 && (
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-semibold text-gray-800 mb-4">Kategorie-Uebersicht</h3>
          <div className="space-y-3">
            {Object.entries(result.category_scores)
              .sort(([, a], [, b]) => a - b)
              .map(([cat, score]) => (
                <div key={cat} className="flex items-center gap-3">
                  <span className="text-sm text-gray-700 w-48 truncate">{CAT_LABELS[cat] || cat}</span>
                  <div className="flex-1 h-3 bg-gray-100 rounded-full overflow-hidden">
                    <div
                      className={`h-full rounded-full ${score >= 80 ? 'bg-green-500' : score >= 50 ? 'bg-yellow-500' : 'bg-red-500'}`}
                      style={{ width: `${score}%` }}
                    />
                  </div>
                  <span className={`text-sm font-bold w-12 text-right ${scoreColor(score)}`}>{score}%</span>
                </div>
              ))}
          </div>
        </div>
      )}

      {/* Cross-Check Findings */}
      {result.cross_check_findings.length > 0 && (
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-semibold text-gray-800 mb-4">
            Dokumenten-Cross-Check
            <span className="ml-2 text-sm font-normal text-gray-400">{result.cross_check_findings.length} Findings</span>
          </h3>
          <div className="space-y-2">
            {result.cross_check_findings.map(f => (
              <div key={f.id} className={`border-l-4 rounded-r-lg p-3 ${
                f.severity === 'CRITICAL' ? 'border-red-500 bg-red-50' :
                f.severity === 'HIGH' ? 'border-orange-500 bg-orange-50' :
                'border-yellow-500 bg-yellow-50'
              }`}>
                <div className="flex items-center gap-2">
                  <span className={`px-2 py-0.5 rounded text-xs font-bold border ${SEV_COLORS[f.severity] || ''}`}>
                    {f.severity}
                  </span>
                  <span className="text-sm font-medium text-gray-900">{f.label}</span>
                </div>
                <p className="text-xs text-gray-600 mt-1 leading-relaxed">{f.hint}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Documents Detail */}
      <div className="bg-white rounded-xl border p-5">
        <h3 className="font-semibold text-gray-800 mb-4">Gepruefte Dokumente</h3>
        <div className="space-y-3">
          {result.documents.map((doc, i) => (
            <div key={i} className="border border-gray-200 rounded-lg overflow-hidden">
              <button
                onClick={() => setExpandedDoc(expandedDoc === i ? null : i)}
                className="w-full text-left p-4 hover:bg-gray-50 flex items-center justify-between"
              >
                <div className="flex items-center gap-3">
                  <span className="px-2 py-0.5 bg-indigo-100 text-indigo-700 rounded text-xs font-bold">
                    {doc.doc_type.toUpperCase()}
                  </span>
                  <span className="font-medium text-gray-900 text-sm">{doc.label}</span>
                </div>
                <div className="flex items-center gap-4">
                  <div className="text-right">
                    <span className={`text-sm font-bold ${scoreColor(doc.completeness_pct)}`}>
                      {doc.completeness_pct}%
                    </span>
                    <span className="text-xs text-gray-400 ml-1">vollstaendig</span>
                  </div>
                  {doc.findings_count > 0 && (
                    <span className="px-2 py-0.5 bg-red-100 text-red-700 rounded-full text-xs font-bold">
                      {doc.findings_count}
                    </span>
                  )}
                  <span className="text-gray-400 text-sm">{expandedDoc === i ? '▲' : '▼'}</span>
                </div>
              </button>

              {expandedDoc === i && (
                <div className="border-t p-4 bg-gray-50">
                  {doc.error ? (
                    <p className="text-red-600 text-sm">{doc.error}</p>
                  ) : (
                    <div className="space-y-1">
                      {doc.checks.filter(c => c.level === 1).map(c => {
                        const l2s = doc.checks.filter(l => l.level === 2 && l.parent === c.id)
                        return (
                          <div key={c.id}>
                            <div className={`flex items-center gap-2 py-1 ${!c.passed && !c.skipped ? 'text-red-700' : ''}`}>
                              <span>{c.passed ? '✓' : c.skipped ? '—' : '✗'}</span>
                              <span className="text-sm">{c.label}</span>
                              <span className={`px-1.5 py-0.5 rounded text-[10px] font-bold ${SEV_COLORS[c.severity] || ''}`}>
                                {c.severity}
                              </span>
                            </div>
                            {!c.passed && !c.skipped && c.hint && (
                              <div className="ml-6 mb-1 text-xs text-red-600 bg-red-50 border-l-2 border-red-300 pl-2 py-1">
                                {c.hint}
                              </div>
                            )}
                            {l2s.map(l2 => (
                              <div key={l2.id} className={`ml-6 flex items-center gap-2 py-0.5 text-xs ${!l2.passed ? 'text-red-600' : 'text-gray-500'}`}>
                                <span>{l2.passed ? '✓' : l2.skipped ? '—' : '✗'}</span>
                                <span>{l2.label}</span>
                              </div>
                            ))}
                          </div>
                        )
                      })}
                    </div>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Findings Detail */}
      {result.findings.length > 0 && (
        <div className="bg-white rounded-xl border p-5">
          <h3 className="font-semibold text-gray-800 mb-4">
            Alle Findings
            <span className="ml-2 text-sm font-normal text-gray-400">{result.findings.length}</span>
          </h3>
          <div className="space-y-2">
            {[...result.findings]
              .sort((a, b) => {
                const order: Record<string, number> = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 }
                return (order[a.severity] ?? 4) - (order[b.severity] ?? 4)
              })
              .map(f => (
                <div key={f.id} className="border border-gray-200 rounded-lg p-3">
                  <div className="flex items-center gap-2 mb-1">
                    <span className={`px-2 py-0.5 rounded text-xs font-bold border ${SEV_COLORS[f.severity] || ''}`}>
                      {f.severity}
                    </span>
                    <span className="text-sm font-medium text-gray-900">{f.title}</span>
                  </div>
                  <div className="text-xs text-gray-400 mb-1">
                    {CAT_LABELS[f.category] || f.category} | {f.document_label}
                  </div>
                  {f.description && (
                    <p className="text-xs text-gray-600 leading-relaxed">{f.description}</p>
                  )}
                </div>
              ))}
          </div>
        </div>
      )}

      {/* Actions */}
      <div className="flex items-center gap-3">
        <button
          onClick={onReset}
          className="px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium"
        >
          Neue Pruefung
        </button>
        {result.report_html && (
          <button
            onClick={() => setShowHtml(!showHtml)}
            className="px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium"
          >
            {showHtml ? 'Protokoll ausblenden' : 'Pruefprotokoll (Druckversion)'}
          </button>
        )}
      </div>

      {/* Print-ready HTML report */}
      {showHtml && result.report_html && (
        <div className="bg-white rounded-xl border p-6 mt-4">
          <div dangerouslySetInnerHTML={{ __html: result.report_html }} />
        </div>
      )}
    </div>
  )
}
