'use client'

import {
  ArrowLeft, ExternalLink, BookOpen, Scale, FileText,
  Eye, CheckCircle2, Trash2, Pencil, Clock,
  ChevronLeft, SkipForward,
} from 'lucide-react'
import { CanonicalControl, EFFORT_LABELS, SeverityBadge, StateBadge, LicenseRuleBadge } from './helpers'

interface ControlDetailProps {
  ctrl: CanonicalControl
  onBack: () => void
  onEdit: () => void
  onDelete: (controlId: string) => void
  onReview: (controlId: string, action: string) => void
  // Review mode navigation
  reviewMode?: boolean
  reviewIndex?: number
  reviewTotal?: number
  onReviewPrev?: () => void
  onReviewNext?: () => void
}

export function ControlDetail({
  ctrl,
  onBack,
  onEdit,
  onDelete,
  onReview,
  reviewMode,
  reviewIndex = 0,
  reviewTotal = 0,
  onReviewPrev,
  onReviewNext,
}: ControlDetailProps) {
  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b border-gray-200 bg-white px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={onBack} className="text-gray-400 hover:text-gray-600">
            <ArrowLeft className="w-5 h-5" />
          </button>
          <div>
            <div className="flex items-center gap-2">
              <span className="text-sm font-mono text-purple-600 bg-purple-50 px-2 py-0.5 rounded">{ctrl.control_id}</span>
              <SeverityBadge severity={ctrl.severity} />
              <StateBadge state={ctrl.release_state} />
              <LicenseRuleBadge rule={ctrl.license_rule} />
            </div>
            <h2 className="text-lg font-semibold text-gray-900 mt-1">{ctrl.title}</h2>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {reviewMode && (
            <div className="flex items-center gap-1 mr-3">
              <button onClick={onReviewPrev} disabled={reviewIndex === 0} className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30">
                <ChevronLeft className="w-4 h-4" />
              </button>
              <span className="text-xs text-gray-500 font-medium">{reviewIndex + 1} / {reviewTotal}</span>
              <button onClick={onReviewNext} disabled={reviewIndex >= reviewTotal - 1} className="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-30">
                <SkipForward className="w-4 h-4" />
              </button>
            </div>
          )}
          <button onClick={onEdit} className="px-3 py-1.5 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50">
            <Pencil className="w-3.5 h-3.5 inline mr-1" />Bearbeiten
          </button>
          <button onClick={() => onDelete(ctrl.control_id)} className="px-3 py-1.5 text-sm text-red-600 border border-red-300 rounded-lg hover:bg-red-50">
            <Trash2 className="w-3.5 h-3.5 inline mr-1" />Loeschen
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6 max-w-4xl mx-auto w-full space-y-6">
        {/* Objective */}
        <section>
          <h3 className="text-sm font-semibold text-gray-900 mb-2">Ziel</h3>
          <p className="text-sm text-gray-700 leading-relaxed">{ctrl.objective}</p>
        </section>

        {/* Rationale */}
        <section>
          <h3 className="text-sm font-semibold text-gray-900 mb-2">Begruendung</h3>
          <p className="text-sm text-gray-700 leading-relaxed">{ctrl.rationale}</p>
        </section>

        {/* Source Info (Rule 1 + 2) */}
        {ctrl.source_citation && (
          <section className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div className="flex items-center gap-2 mb-2">
              <Scale className="w-4 h-4 text-blue-600" />
              <h3 className="text-sm font-semibold text-blue-900">Quellenangabe</h3>
            </div>
            <div className="text-xs text-blue-700 space-y-1">
              {Object.entries(ctrl.source_citation).map(([k, v]) => (
                <p key={k}><span className="font-medium">{k}:</span> {v}</p>
              ))}
            </div>
            {ctrl.source_original_text && (
              <details className="mt-3">
                <summary className="text-xs text-blue-600 cursor-pointer hover:text-blue-800">Originaltext anzeigen</summary>
                <p className="text-xs text-gray-600 mt-2 p-2 bg-white rounded border border-blue-100 leading-relaxed max-h-40 overflow-y-auto">
                  {ctrl.source_original_text}
                </p>
              </details>
            )}
          </section>
        )}

        {/* Scope */}
        {(ctrl.scope.platforms?.length || ctrl.scope.components?.length || ctrl.scope.data_classes?.length) ? (
          <section>
            <h3 className="text-sm font-semibold text-gray-900 mb-2">Geltungsbereich</h3>
            <div className="grid grid-cols-3 gap-4 text-xs">
              {ctrl.scope.platforms?.length ? (
                <div><span className="text-gray-500">Plattformen:</span> <span className="text-gray-700">{ctrl.scope.platforms.join(', ')}</span></div>
              ) : null}
              {ctrl.scope.components?.length ? (
                <div><span className="text-gray-500">Komponenten:</span> <span className="text-gray-700">{ctrl.scope.components.join(', ')}</span></div>
              ) : null}
              {ctrl.scope.data_classes?.length ? (
                <div><span className="text-gray-500">Datenklassen:</span> <span className="text-gray-700">{ctrl.scope.data_classes.join(', ')}</span></div>
              ) : null}
            </div>
          </section>
        ) : null}

        {/* Requirements */}
        {ctrl.requirements.length > 0 && (
          <section>
            <h3 className="text-sm font-semibold text-gray-900 mb-2">Anforderungen</h3>
            <ol className="list-decimal list-inside space-y-1">
              {ctrl.requirements.map((r, i) => (
                <li key={i} className="text-sm text-gray-700">{r}</li>
              ))}
            </ol>
          </section>
        )}

        {/* Test Procedure */}
        {ctrl.test_procedure.length > 0 && (
          <section>
            <h3 className="text-sm font-semibold text-gray-900 mb-2">Pruefverfahren</h3>
            <ol className="list-decimal list-inside space-y-1">
              {ctrl.test_procedure.map((s, i) => (
                <li key={i} className="text-sm text-gray-700">{s}</li>
              ))}
            </ol>
          </section>
        )}

        {/* Evidence */}
        {ctrl.evidence.length > 0 && (
          <section>
            <h3 className="text-sm font-semibold text-gray-900 mb-2">Nachweise</h3>
            <div className="space-y-2">
              {ctrl.evidence.map((ev, i) => (
                <div key={i} className="flex items-start gap-2 text-sm text-gray-700">
                  <FileText className="w-4 h-4 text-gray-400 flex-shrink-0 mt-0.5" />
                  <div><span className="font-medium">{ev.type}:</span> {ev.description}</div>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* Meta */}
        <section className="grid grid-cols-3 gap-4 text-xs text-gray-500">
          {ctrl.risk_score !== null && <div>Risiko-Score: <span className="text-gray-700 font-medium">{ctrl.risk_score}</span></div>}
          {ctrl.implementation_effort && <div>Aufwand: <span className="text-gray-700 font-medium">{EFFORT_LABELS[ctrl.implementation_effort] || ctrl.implementation_effort}</span></div>}
          {ctrl.tags.length > 0 && (
            <div className="col-span-3 flex items-center gap-1 flex-wrap">
              {ctrl.tags.map(t => (
                <span key={t} className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">{t}</span>
              ))}
            </div>
          )}
        </section>

        {/* Open Anchors */}
        <section className="bg-green-50 border border-green-200 rounded-lg p-4">
          <div className="flex items-center gap-2 mb-3">
            <BookOpen className="w-4 h-4 text-green-700" />
            <h3 className="text-sm font-semibold text-green-900">Open-Source-Referenzen ({ctrl.open_anchors.length})</h3>
          </div>
          {ctrl.open_anchors.length > 0 ? (
            <div className="space-y-2">
              {ctrl.open_anchors.map((anchor, i) => (
                <div key={i} className="flex items-center gap-2 text-sm">
                  <ExternalLink className="w-3.5 h-3.5 text-green-600 flex-shrink-0" />
                  <span className="font-medium text-green-800">{anchor.framework}</span>
                  <span className="text-green-700">{anchor.ref}</span>
                  {anchor.url && (
                    <a href={anchor.url} target="_blank" rel="noopener noreferrer" className="text-green-600 hover:text-green-800 underline text-xs ml-auto">
                      Link
                    </a>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-green-600">Keine Referenzen vorhanden.</p>
          )}
        </section>

        {/* Generation Metadata (internal) */}
        {ctrl.generation_metadata && (
          <section className="bg-gray-50 border border-gray-200 rounded-lg p-4">
            <div className="flex items-center gap-2 mb-2">
              <Clock className="w-4 h-4 text-gray-500" />
              <h3 className="text-sm font-semibold text-gray-700">Generierungsdetails (intern)</h3>
            </div>
            <div className="text-xs text-gray-600 space-y-1">
              <p>Pfad: {String(ctrl.generation_metadata.processing_path || '-')}</p>
              {ctrl.generation_metadata.similarity_status && (
                <p className="text-red-600">Similarity: {String(ctrl.generation_metadata.similarity_status)}</p>
              )}
              {Array.isArray(ctrl.generation_metadata.similar_controls) && (
                <div>
                  <p className="font-medium">Aehnliche Controls:</p>
                  {(ctrl.generation_metadata.similar_controls as Array<Record<string, unknown>>).map((s, i) => (
                    <p key={i} className="ml-2">{String(s.control_id)} — {String(s.title)} ({String(s.similarity)})</p>
                  ))}
                </div>
              )}
            </div>
          </section>
        )}

        {/* Review Actions */}
        {['needs_review', 'too_close', 'duplicate'].includes(ctrl.release_state) && (
          <section className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div className="flex items-center gap-2 mb-3">
              <Eye className="w-4 h-4 text-yellow-700" />
              <h3 className="text-sm font-semibold text-yellow-900">Review erforderlich</h3>
              {reviewMode && (
                <span className="text-xs text-yellow-600 ml-auto">Review-Modus aktiv</span>
              )}
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => onReview(ctrl.control_id, 'approve')}
                className="px-3 py-1.5 text-sm text-white bg-green-600 rounded-lg hover:bg-green-700"
              >
                <CheckCircle2 className="w-3.5 h-3.5 inline mr-1" />
                Akzeptieren
              </button>
              <button
                onClick={() => onReview(ctrl.control_id, 'reject')}
                className="px-3 py-1.5 text-sm text-white bg-red-600 rounded-lg hover:bg-red-700"
              >
                <Trash2 className="w-3.5 h-3.5 inline mr-1" />
                Ablehnen
              </button>
              <button
                onClick={onEdit}
                className="px-3 py-1.5 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                <Pencil className="w-3.5 h-3.5 inline mr-1" />
                Ueberarbeiten
              </button>
            </div>
          </section>
        )}
      </div>
    </div>
  )
}
