'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  ArrowLeft, BookOpen, ExternalLink, FileText, Eye,
  Clock, ChevronLeft, SkipForward, Pencil, Trash2, Scale, GitMerge,
} from 'lucide-react'
import {
  CanonicalControl, EFFORT_LABELS, BACKEND_URL,
  SeverityBadge, StateBadge, LicenseRuleBadge, VerificationMethodBadge, CategoryBadge,
  EvidenceTypeBadge, TargetAudienceBadge, GenerationStrategyBadge, ObligationTypeBadge,
  isEigenentwicklung,
  ObligationInfo, DocumentReference, MergedDuplicate, RegulationSummary,
} from './helpers'
import { ControlSourceCitation } from './ControlSourceCitation'
import { ControlTraceability } from './ControlTraceability'
import { ControlRegulatorySection } from './ControlRegulatorySection'
import { ControlSimilarControls } from './ControlSimilarControls'
import { ControlReviewActions } from './ControlReviewActions'

// Defensive coercer: some canonical_controls rows have evidence/tags/etc.
// as JSON-encoded strings instead of arrays. .map() on a string throws.
function toArray<T = unknown>(v: unknown): T[] {
  if (Array.isArray(v)) return v as T[]
  if (typeof v === 'string' && v.trim().startsWith('[')) {
    try { const p = JSON.parse(v); return Array.isArray(p) ? p : [] } catch { return [] }
  }
  return []
}

interface SimilarControl {
  control_id: string; title: string; severity: string; release_state: string;
  tags: string[]; license_rule: number | null; verification_method: string | null;
  category: string | null; similarity: number;
}

interface ParentLink {
  parent_control_id: string; parent_title: string; link_type: string; confidence: number;
  source_regulation: string | null; source_article: string | null;
  parent_citation: Record<string, string> | null;
  obligation: { text: string; action: string; object: string; normative_strength: string } | null;
}

interface TraceabilityData {
  control_id: string; title: string; is_atomic: boolean; parent_links: ParentLink[];
  children: Array<{ control_id: string; title: string; category: string; severity: string; decomposition_method: string }>;
  source_count: number; obligations?: ObligationInfo[]; obligation_count?: number;
  document_references?: DocumentReference[]; merged_duplicates?: MergedDuplicate[];
  merged_duplicates_count?: number; regulations_summary?: RegulationSummary[];
}

interface V1Match {
  matched_control_id: string; matched_title: string; matched_objective: string;
  matched_severity: string; matched_category: string; matched_source: string | null;
  matched_article: string | null; matched_source_citation: Record<string, string> | null;
  similarity_score: number; match_rank: number; match_method: string;
}

interface ControlDetailProps {
  ctrl: CanonicalControl
  onBack: () => void
  onEdit: () => void
  onDelete: (controlId: string) => void
  onReview: (controlId: string, action: string) => void
  onRefresh?: () => void
  onNavigateToControl?: (controlId: string) => void
  onCompare?: (ctrl: CanonicalControl, matches: V1Match[]) => void
  reviewMode?: boolean
  reviewIndex?: number
  reviewTotal?: number
  onReviewPrev?: () => void
  onReviewNext?: () => void
}

export function ControlDetail({
  ctrl, onBack, onEdit, onDelete, onReview, onRefresh, onNavigateToControl, onCompare,
  reviewMode, reviewIndex = 0, reviewTotal = 0, onReviewPrev, onReviewNext,
}: ControlDetailProps) {
  const [similarControls, setSimilarControls] = useState<SimilarControl[]>([])
  const [loadingSimilar, setLoadingSimilar] = useState(false)
  const [selectedDuplicates, setSelectedDuplicates] = useState<Set<string>>(new Set())
  const [merging, setMerging] = useState(false)
  const [traceability, setTraceability] = useState<TraceabilityData | null>(null)
  const [loadingTrace, setLoadingTrace] = useState(false)
  const [v1Matches, setV1Matches] = useState<V1Match[]>([])
  const [loadingV1, setLoadingV1] = useState(false)
  const eigenentwicklung = isEigenentwicklung(ctrl)

  const loadTraceability = useCallback(async () => {
    setLoadingTrace(true)
    try {
      let res = await fetch(`${BACKEND_URL}?endpoint=provenance&id=${ctrl.control_id}`)
      if (!res.ok) res = await fetch(`${BACKEND_URL}?endpoint=traceability&id=${ctrl.control_id}`)
      if (res.ok) setTraceability(await res.json())
    } catch { /* ignore */ }
    finally { setLoadingTrace(false) }
  }, [ctrl.control_id])

  const loadV1Matches = useCallback(async () => {
    if (!eigenentwicklung) { setV1Matches([]); return }
    setLoadingV1(true)
    try {
      const res = await fetch(`${BACKEND_URL}?endpoint=v1-matches&id=${ctrl.control_id}`)
      if (res.ok) setV1Matches(await res.json()); else setV1Matches([])
    } catch { setV1Matches([]) }
    finally { setLoadingV1(false) }
  }, [ctrl.control_id, eigenentwicklung])

  const loadSimilarControls = async () => {
    setLoadingSimilar(true)
    try {
      const res = await fetch(`${BACKEND_URL}?endpoint=similar&id=${ctrl.control_id}`)
      if (res.ok) setSimilarControls(await res.json())
    } catch { /* ignore */ }
    finally { setLoadingSimilar(false) }
  }

  useEffect(() => {
    loadSimilarControls(); loadTraceability(); loadV1Matches()
    setSelectedDuplicates(new Set())
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ctrl.control_id])

  const toggleDuplicate = (controlId: string) => {
    setSelectedDuplicates(prev => { const n = new Set(prev); if (n.has(controlId)) n.delete(controlId); else n.add(controlId); return n })
  }

  const handleMergeDuplicates = async () => {
    if (selectedDuplicates.size === 0) return
    if (!confirm(`${selectedDuplicates.size} Controls als Duplikate markieren und Tags/Anchors in ${ctrl.control_id} zusammenfuehren?`)) return
    setMerging(true)
    try {
      for (const dupId of selectedDuplicates) {
        await fetch(`${BACKEND_URL}?endpoint=update-control&id=${dupId}`, {
          method: 'PUT', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ release_state: 'deprecated' }),
        })
      }
      if (onRefresh) onRefresh()
      setSelectedDuplicates(new Set()); loadSimilarControls()
    } catch { alert('Fehler beim Zusammenfuehren') }
    finally { setMerging(false) }
  }

  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} />
              <VerificationMethodBadge method={ctrl.verification_method} />
              <CategoryBadge category={ctrl.category} />
              <EvidenceTypeBadge type={ctrl.evidence_type} />
              <TargetAudienceBadge audience={ctrl.target_audience} />
              <GenerationStrategyBadge strategy={ctrl.generation_strategy} pipelineInfo={ctrl} />
              <ObligationTypeBadge type={ctrl.generation_metadata?.obligation_type as string} />
            </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">
        <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>
        <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>

        <ControlSourceCitation ctrl={ctrl} />

        {eigenentwicklung && (
          <ControlRegulatorySection ctrl={ctrl} v1Matches={v1Matches} loadingV1={loadingV1}
            onNavigateToControl={onNavigateToControl} onCompare={onCompare} />
        )}

        <ControlTraceability ctrl={ctrl} traceability={traceability} loadingTrace={loadingTrace}
          onNavigateToControl={onNavigateToControl} />

        {!ctrl.source_citation && toArray(ctrl.open_anchors).length > 0 && (
          <section className="bg-amber-50 border border-amber-200 rounded-lg p-3">
            <div className="flex items-center gap-2">
              <Scale className="w-4 h-4 text-amber-600" />
              <div className="flex-1">
                <p className="text-xs text-amber-800 font-medium">Abgeleitet aus regulatorischen Anforderungen</p>
                <p className="text-xs text-amber-700 mt-0.5">
                  Dieser Control wurde aus geschuetzten Quellen reformuliert (z.B. BSI Grundschutz, ISO 27001).
                  Die konkreten Massnahmen leiten sich aus den Open-Source-Referenzen unten ab.
                </p>
              </div>
            </div>
          </section>
        )}

        {(toArray(ctrl.scope?.platforms).length || toArray(ctrl.scope?.components).length || toArray(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">
              {toArray<string>(ctrl.scope?.platforms).length ? <div><span className="text-gray-500">Plattformen:</span> <span className="text-gray-700">{toArray<string>(ctrl.scope?.platforms).join(', ')}</span></div> : null}
              {toArray<string>(ctrl.scope?.components).length ? <div><span className="text-gray-500">Komponenten:</span> <span className="text-gray-700">{toArray<string>(ctrl.scope?.components).join(', ')}</span></div> : null}
              {toArray<string>(ctrl.scope?.data_classes).length ? <div><span className="text-gray-500">Datenklassen:</span> <span className="text-gray-700">{toArray<string>(ctrl.scope?.data_classes).join(', ')}</span></div> : null}
            </div>
          </section>
        ) : null}

        {toArray<string>(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">{toArray<string>(ctrl.requirements).map((r, i) => <li key={i} className="text-sm text-gray-700">{r}</li>)}</ol>
          </section>
        )}

        {toArray<string>(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">{toArray<string>(ctrl.test_procedure).map((s, i) => <li key={i} className="text-sm text-gray-700">{s}</li>)}</ol>
          </section>
        )}

        {toArray(ctrl.evidence).length > 0 && (
          <section>
            <h3 className="text-sm font-semibold text-gray-900 mb-2">Nachweise</h3>
            <div className="space-y-2">
              {toArray<string | { type?: string; description?: string }>(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" />
                  {typeof ev === 'string' ? <div>{ev}</div> : <div><span className="font-medium">{ev.type}:</span> {ev.description}</div>}
                </div>
              ))}
            </div>
          </section>
        )}

        <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>}
          {toArray<string>(ctrl.tags).length > 0 && (
            <div className="col-span-3 flex items-center gap-1 flex-wrap">
              {toArray<string>(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>

        <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 ({toArray(ctrl.open_anchors).length})</h3>
          </div>
          {toArray(ctrl.open_anchors).length > 0 ? (
            <div className="space-y-2">
              {toArray<{ framework?: string; ref?: string; url?: string }>(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>

        {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">
              {!!ctrl.generation_metadata.processing_path && <p>Pfad: {String(ctrl.generation_metadata.processing_path)}</p>}
              {!!ctrl.generation_metadata.decomposition_method && <p>Methode: {String(ctrl.generation_metadata.decomposition_method)}</p>}
              {!!ctrl.generation_metadata.pass0b_model && <p>LLM: {String(ctrl.generation_metadata.pass0b_model)}</p>}
              {!!ctrl.generation_metadata.obligation_type && <p>Obligation-Typ: {String(ctrl.generation_metadata.obligation_type)}</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>
        )}

        <ControlSimilarControls
          ctrl={ctrl} similarControls={similarControls} loadingSimilar={loadingSimilar}
          selectedDuplicates={selectedDuplicates} merging={merging}
          onToggleDuplicate={toggleDuplicate} onMergeDuplicates={handleMergeDuplicates}
        />

        <ControlReviewActions
          controlId={ctrl.control_id} releaseState={ctrl.release_state}
          reviewMode={reviewMode} onReview={onReview} onEdit={onEdit}
        />
      </div>
    </div>
  )
}
