'use client'

import React, { useState, useEffect } from 'react'
import { useParams } from 'next/navigation'
import Link from 'next/link'
import { ZoneBadge } from '@/components/sdk/compliance-optimizer/ZoneBadge'
import { DimensionZoneTable } from '@/components/sdk/compliance-optimizer/DimensionZoneTable'
import { ConfigComparison } from '@/components/sdk/compliance-optimizer/ConfigComparison'
import { OptimizationScoreCard } from '@/components/sdk/compliance-optimizer/OptimizationScoreCard'

export default function OptimizationDetailPage() {
  const params = useParams()
  const id = params?.id as string
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [activeVariant, setActiveVariant] = useState(0)

  useEffect(() => {
    if (!id) return
    fetch(`/api/sdk/v1/maximizer/optimizations/${id}`)
      .then((r) => r.ok ? r.json() : null)
      .then(setData)
      .finally(() => setLoading(false))
  }, [id])

  if (loading) return <div className="max-w-6xl mx-auto p-6 text-gray-500">Laden...</div>
  if (!data) return <div className="max-w-6xl mx-auto p-6 text-red-600">Optimierung nicht gefunden.</div>

  const maxSafe = data.max_safe_config
  const variants = data.variants || []
  const zones = data.zone_map || {}
  const controls = data.original_evaluation?.required_controls || []
  const patterns = data.original_evaluation?.required_patterns || []
  const triggered = data.original_evaluation?.triggered_rules || []

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <Link href="/sdk/compliance-optimizer" className="text-sm text-blue-600 hover:underline">← Zurueck</Link>
          <h1 className="text-2xl font-bold text-gray-900 mt-1">{data.title || 'Optimierung'}</h1>
          <p className="text-sm text-gray-500">{new Date(data.created_at).toLocaleString('de-DE')} — v{data.constraint_version}</p>
          {data.assessment_id && (
            <Link href={`/sdk/use-cases/${data.assessment_id}`} className="text-sm text-purple-600 hover:underline">
              Basierend auf Assessment
            </Link>
          )}
        </div>
        <ZoneBadge zone={data.is_compliant ? 'SAFE' : 'FORBIDDEN'} />
      </div>

      {/* 3-Zone Summary */}
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <h2 className="text-lg font-semibold text-gray-800 mb-3">3-Zonen-Analyse</h2>
        <DimensionZoneTable zoneMap={zones} />
      </div>

      {/* Optimization Result */}
      {maxSafe && (
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <h2 className="text-lg font-semibold text-gray-800 mb-3">Optimierte Konfiguration</h2>
          <OptimizationScoreCard
            safetyScore={maxSafe.safety_score}
            utilityScore={maxSafe.utility_score}
            compositeScore={maxSafe.composite_score}
            deltaCount={maxSafe.delta_count}
          />
          <div className="mt-4">
            <ConfigComparison deltas={maxSafe.deltas || []} />
          </div>
          {maxSafe.rationale && (
            <p className="mt-3 text-sm text-gray-600 italic">{maxSafe.rationale}</p>
          )}
        </div>
      )}

      {/* Alternative Variants */}
      {variants.length > 1 && (
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <h2 className="text-lg font-semibold text-gray-800 mb-3">Alternative Varianten ({variants.length})</h2>
          <div className="flex gap-2 mb-3">
            {variants.map((v: any, i: number) => (
              <button key={i} onClick={() => setActiveVariant(i)}
                className={`px-3 py-1 text-sm rounded ${i === activeVariant ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                Variante {i + 1}
              </button>
            ))}
          </div>
          {variants[activeVariant] && (
            <div>
              <div className="flex items-center gap-4 mb-2 text-sm text-gray-600">
                <span>Sicherheit: {variants[activeVariant].safety_score}</span>
                <span>Nutzen: {variants[activeVariant].utility_score}</span>
                <span>Gesamt: {Math.round(variants[activeVariant].composite_score)}</span>
              </div>
              <ConfigComparison deltas={variants[activeVariant].deltas || []} />
              {variants[activeVariant].rationale && (
                <p className="mt-2 text-sm text-gray-500 italic">{variants[activeVariant].rationale}</p>
              )}
            </div>
          )}
        </div>
      )}

      {/* Required Controls & Patterns */}
      {(controls.length > 0 || patterns.length > 0) && (
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <h2 className="text-lg font-semibold text-gray-800 mb-3">Erforderliche Massnahmen</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {controls.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">Controls</h4>
                <ul className="space-y-1">
                  {controls.map((c: string, i: number) => (
                    <li key={i} className="text-sm text-gray-600 flex items-center gap-2">
                      <span className="w-1.5 h-1.5 bg-blue-500 rounded-full" />{c}
                    </li>
                  ))}
                </ul>
              </div>
            )}
            {patterns.length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">Architektur-Patterns</h4>
                <ul className="space-y-1">
                  {patterns.map((p: string, i: number) => (
                    <li key={i} className="text-sm text-gray-600 flex items-center gap-2">
                      <span className="w-1.5 h-1.5 bg-purple-500 rounded-full" />{p}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Triggered Rules (Audit Trail) */}
      {triggered.length > 0 && (
        <div className="bg-white border border-gray-200 rounded-lg p-4">
          <h2 className="text-lg font-semibold text-gray-800 mb-3">Ausgeloeste Regeln ({triggered.length})</h2>
          <div className="space-y-2">
            {triggered.map((r: any, i: number) => (
              <div key={i} className="flex items-start gap-3 text-sm border-b border-gray-100 pb-2">
                <span className="font-mono text-xs text-gray-400 min-w-[120px]">{r.rule_id}</span>
                <span className="text-gray-700">{r.title}</span>
                <span className="text-gray-400 ml-auto text-xs">{r.article_ref}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
