'use client'

import React from 'react'
import Link from 'next/link'
import { useSDK, SDK_PACKAGES, getStepsForPackage } from '@/lib/sdk'
import { ProjectSelector } from '@/components/sdk/ProjectSelector/ProjectSelector'
import { RegulatoryNewsFeed } from '@/components/sdk/regulatory-news/RegulatoryNewsFeed'
import { PresetSection } from './_components/PresetSection'
import type { SDKPackageId } from '@/lib/sdk/types'

// =============================================================================
// DASHBOARD CARDS
// =============================================================================

function StatCard({ title, value, subtitle, icon, color }: {
  title: string; value: string | number; subtitle: string; icon: React.ReactNode; color: string
}) {
  return (
    <div className="bg-white rounded-xl border border-gray-200 p-6">
      <div className="flex items-start justify-between">
        <div>
          <p className="text-sm text-gray-500">{title}</p>
          <p className="mt-1 text-3xl font-bold text-gray-900">{value}</p>
          <p className="mt-1 text-sm text-gray-500">{subtitle}</p>
        </div>
        <div className={`p-3 rounded-lg ${color}`}>{icon}</div>
      </div>
    </div>
  )
}

function PackageCard({ pkg, completion, stepsCount, isLocked, projectId }: {
  pkg: (typeof SDK_PACKAGES)[number]; completion: number; stepsCount: number; isLocked: boolean; projectId?: string
}) {
  const steps = getStepsForPackage(pkg.id)
  const firstStep = steps[0]
  const baseHref = firstStep?.url || '/sdk'
  const href = projectId ? `${baseHref}?project=${projectId}` : baseHref

  const content = (
    <div className={`block bg-white rounded-xl border-2 p-6 transition-all ${
      isLocked ? 'border-gray-100 opacity-60 cursor-not-allowed'
        : completion === 100 ? 'border-green-200 hover:border-green-300 hover:shadow-lg'
        : 'border-gray-200 hover:border-purple-300 hover:shadow-lg'
    }`}>
      <div className="flex items-start gap-4">
        <div className={`w-14 h-14 rounded-xl flex items-center justify-center text-2xl ${
          isLocked ? 'bg-gray-100 text-gray-400' : completion === 100 ? 'bg-green-100 text-green-600' : 'bg-purple-100 text-purple-600'
        }`}>
          {isLocked ? (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
          ) : completion === 100 ? (
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>
          ) : pkg.icon}
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-500">{pkg.order}.</span>
            <h3 className="text-lg font-semibold text-gray-900">{pkg.name}</h3>
          </div>
          <p className="mt-1 text-sm text-gray-500">{pkg.description}</p>
          <div className="mt-4">
            <div className="flex items-center justify-between text-sm mb-1">
              <span className="text-gray-500">{stepsCount} Schritte</span>
              <span className={`font-medium ${completion === 100 ? 'text-green-600' : 'text-purple-600'}`}>{completion}%</span>
            </div>
            <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
              <div className={`h-full rounded-full transition-all duration-500 ${completion === 100 ? 'bg-green-500' : 'bg-purple-600'}`} style={{ width: `${completion}%` }} />
            </div>
          </div>
          {!isLocked && <p className="mt-3 text-xs text-gray-400">Ergebnis: {pkg.result}</p>}
        </div>
      </div>
    </div>
  )

  return isLocked ? content : <Link href={href}>{content}</Link>
}

function QuickActionCard({ title, description, icon, href, color, projectId }: {
  title: string; description: string; icon: React.ReactNode; href: string; color: string; projectId?: string
}) {
  const finalHref = projectId ? `${href}?project=${projectId}` : href
  return (
    <Link href={finalHref} className="flex items-center gap-4 p-4 bg-white rounded-xl border border-gray-200 hover:border-purple-300 hover:shadow-md transition-all">
      <div className={`p-3 rounded-lg ${color}`}>{icon}</div>
      <div>
        <h4 className="font-medium text-gray-900">{title}</h4>
        <p className="text-sm text-gray-500">{description}</p>
      </div>
      <svg className="w-5 h-5 text-gray-400 ml-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
      </svg>
    </Link>
  )
}

// =============================================================================
// MAIN DASHBOARD
// =============================================================================

export default function SDKDashboard() {
  const { state, packageCompletion, completionPercentage, setCustomerType, projectId } = useSDK()
  const effectiveCustomerType = state.customerType || 'new'

  if (!projectId) return <ProjectSelector />

  const totalSteps = SDK_PACKAGES.reduce((sum, pkg) => {
    const steps = getStepsForPackage(pkg.id)
    return sum + steps.filter(s => !(s.id === 'import' && effectiveCustomerType === 'new')).length
  }, 0)

  const completedCheckpoints = Object.values(state.checkpoints).filter(cp => cp.passed).length
  const totalRisks = state.risks.length
  const criticalRisks = state.risks.filter(r => r.severity === 'CRITICAL' || r.severity === 'HIGH').length

  const isPackageLocked = (packageId: SDKPackageId): boolean => {
    if (state.preferences?.allowParallelWork) return false
    const pkg = SDK_PACKAGES.find(p => p.id === packageId)
    if (!pkg || pkg.order === 1) return false
    const prevPkg = SDK_PACKAGES.find(p => p.order === pkg.order - 1)
    if (!prevPkg) return false
    return packageCompletion[prevPkg.id] < 100
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">AI Compliance SDK</h1>
          <p className="mt-1 text-gray-500">
            {effectiveCustomerType === 'new' ? 'Neukunden-Modus: Erstellen Sie alle Compliance-Dokumente von Grund auf.' : 'Bestandskunden-Modus: Erweitern Sie bestehende Dokumente.'}
          </p>
        </div>
        <button onClick={() => setCustomerType(effectiveCustomerType === 'new' ? 'existing' : 'new')} className="text-sm text-purple-600 hover:text-purple-700 underline">
          {effectiveCustomerType === 'new' ? 'Zu Bestandskunden wechseln' : 'Zu Neukunden wechseln'}
        </button>
      </div>

      {/* Industry Presets with Document Preview */}
      <PresetSection projectId={projectId} />

      {/* Applicable Regulations Card */}
      {state.complianceScope?.decision && (
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-green-100 rounded-lg">
                <svg className="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                </svg>
              </div>
              <div>
                <h3 className="font-semibold text-gray-900">Erkannte Regulierungen</h3>
                <p className="text-xs text-gray-500">Basierend auf Ihrem Scope-Profiling (Level {state.complianceScope.decision.determinedLevel})</p>
              </div>
            </div>
            <Link href={projectId ? `/sdk/compliance-scope?project=${projectId}` : '/sdk/compliance-scope'}
              className="text-xs text-purple-600 hover:underline">
              Details & Anpassen
            </Link>
          </div>
          <div className="flex flex-wrap gap-2">
            {(state.complianceScope.decision.requiredDocuments || []).length > 0 ? (
              ['DSGVO', 'AI Act', 'NIS2', 'HinSchG', 'TTDSG'].filter(reg => {
                const docs = state.complianceScope?.decision?.requiredDocuments || []
                const triggers = state.complianceScope?.decision?.triggeredHardTriggers || []
                if (reg === 'DSGVO') return true
                if (reg === 'AI Act') return triggers.some((t) => t.ruleId.toLowerCase().includes('ai') || t.ruleId.toLowerCase().includes('ki'))
                if (reg === 'NIS2') return triggers.some((t) => t.ruleId.toLowerCase().includes('nis') || t.ruleId.toLowerCase().includes('kritisch'))
                if (reg === 'HinSchG') return triggers.some((t) => t.ruleId.toLowerCase().includes('whistleblower') || t.ruleId.toLowerCase().includes('hinweis'))
                return false
              }).map(reg => (
                <span key={reg} className="px-3 py-1.5 bg-green-50 text-green-700 border border-green-200 rounded-lg text-sm font-medium">
                  {reg}
                </span>
              ))
            ) : (
              <span className="px-3 py-1.5 bg-green-50 text-green-700 border border-green-200 rounded-lg text-sm font-medium">DSGVO</span>
            )}
          </div>
        </div>
      )}
      {!state.complianceScope?.decision && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-5 flex items-center gap-4">
          <div className="p-2 bg-amber-100 rounded-lg flex-shrink-0">
            <svg className="w-5 h-5 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
          </div>
          <div>
            <h3 className="font-semibold text-amber-800">Scope-Profiling noch nicht abgeschlossen</h3>
            <p className="text-sm text-amber-700">
              Fuehren Sie das <Link href={projectId ? `/sdk/compliance-scope?project=${projectId}` : '/sdk/compliance-scope'} className="underline font-medium">Scope-Profiling</Link> durch um zu erfahren welche Regulierungen fuer Ihr Unternehmen gelten.
            </p>
          </div>
        </div>
      )}

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard title="Gesamtfortschritt" value={`${completionPercentage}%`} subtitle={`${state.completedSteps.length} von ${totalSteps} Schritten`}
          icon={<svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>} color="bg-purple-50" />
        <StatCard title="Use Cases" value={state.useCases.length} subtitle={state.useCases.length === 0 ? 'Noch keine erstellt' : 'Erfasst'}
          icon={<svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" /></svg>} color="bg-blue-50" />
        <StatCard title="Checkpoints" value={`${completedCheckpoints}/${totalSteps}`} subtitle="Validiert"
          icon={<svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>} color="bg-green-50" />
        <StatCard title="Risiken" value={totalRisks} subtitle={criticalRisks > 0 ? `${criticalRisks} kritisch` : 'Keine kritischen'}
          icon={<svg className="w-6 h-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>} color="bg-orange-50" />
      </div>

      {/* Bestandskunden: Gap Analysis Banner */}
      {effectiveCustomerType === 'existing' && state.importedDocuments.length === 0 && (
        <div className="bg-gradient-to-r from-indigo-50 to-purple-50 border border-indigo-200 rounded-xl p-6">
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 bg-indigo-100 rounded-xl flex items-center justify-center flex-shrink-0"><span className="text-2xl">📄</span></div>
            <div className="flex-1">
              <h3 className="text-lg font-semibold text-gray-900">Bestehende Dokumente importieren</h3>
              <p className="mt-1 text-gray-600">Laden Sie Ihre vorhandenen Compliance-Dokumente hoch. Unsere KI analysiert sie und zeigt Ihnen, welche Erweiterungen erforderlich sind.</p>
              <Link href={projectId ? `/sdk/import?project=${projectId}` : '/sdk/import'} className="inline-flex items-center gap-2 mt-4 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" /></svg>
                Dokumente hochladen
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* Gap Analysis Results */}
      {state.gapAnalysis && (
        <div className="bg-white border border-gray-200 rounded-xl p-6">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center"><span className="text-xl">📊</span></div>
            <div>
              <h3 className="font-semibold text-gray-900">Gap-Analyse Ergebnis</h3>
              <p className="text-sm text-gray-500">{state.gapAnalysis.totalGaps} Luecken gefunden</p>
            </div>
          </div>
          <div className="grid grid-cols-4 gap-4">
            <div className="text-center p-3 bg-red-50 rounded-lg"><div className="text-2xl font-bold text-red-600">{state.gapAnalysis.criticalGaps}</div><div className="text-xs text-red-600">Kritisch</div></div>
            <div className="text-center p-3 bg-orange-50 rounded-lg"><div className="text-2xl font-bold text-orange-600">{state.gapAnalysis.highGaps}</div><div className="text-xs text-orange-600">Hoch</div></div>
            <div className="text-center p-3 bg-yellow-50 rounded-lg"><div className="text-2xl font-bold text-yellow-600">{state.gapAnalysis.mediumGaps}</div><div className="text-xs text-yellow-600">Mittel</div></div>
            <div className="text-center p-3 bg-green-50 rounded-lg"><div className="text-2xl font-bold text-green-600">{state.gapAnalysis.lowGaps}</div><div className="text-xs text-green-600">Niedrig</div></div>
          </div>
        </div>
      )}

      <RegulatoryNewsFeed businessModel={state.companyProfile?.businessModel as string} />

      {/* 5 Packages */}
      <div>
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Compliance-Pakete</h2>
        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
          {SDK_PACKAGES.map(pkg => {
            const steps = getStepsForPackage(pkg.id)
            const visibleSteps = steps.filter(s => !(s.id === 'import' && effectiveCustomerType === 'new'))
            return <PackageCard key={pkg.id} pkg={pkg} completion={packageCompletion[pkg.id]} stepsCount={visibleSteps.length} isLocked={isPackageLocked(pkg.id)} projectId={projectId} />
          })}
        </div>
      </div>

      {/* Quick Actions */}
      <div>
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Schnellaktionen</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <QuickActionCard title="Neuen Use Case erstellen" description="Starten Sie den 5-Schritte-Wizard"
            icon={<svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>}
            href="/sdk/advisory-board" color="bg-purple-50" projectId={projectId} />
          {/* "Security Screening" entfernt: Repo-Scanning (SBOM/SAST/DAST/Vuln) läuft
              extern im Compliance-Scanner (CERTifAI); das Ergebnis wird dort angezeigt. */}
          <QuickActionCard title="DSFA generieren" description="Datenschutz-Folgenabschaetzung erstellen"
            icon={<svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>}
            href="/sdk/dsfa" color="bg-blue-50" projectId={projectId} />
          <QuickActionCard title="Legal RAG" description="Rechtliche Fragen stellen und Antworten erhalten"
            icon={<svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16l2.879-2.879m0 0a3 3 0 104.243-4.242 3 3 0 00-4.243 4.242zM21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>}
            href="/sdk/rag" color="bg-green-50" projectId={projectId} />
        </div>
      </div>

      {/* Compliance Report Download */}
      <div className="bg-gradient-to-r from-purple-50 to-indigo-50 border border-purple-200 rounded-xl p-6 flex items-center justify-between">
        <div>
          <h3 className="font-semibold text-gray-900">Compliance-Report</h3>
          <p className="text-sm text-gray-500 mt-1">Umfassender PDF-Bericht ueber alle Module, Rollen, Risiken und Massnahmen.</p>
        </div>
        <button
          onClick={() => {
            const url = `/api/sdk/v1/compliance/report/pdf${projectId ? `?project_id=${projectId}` : ''}`
            window.open(url, '_blank')
          }}
          className="px-5 py-2.5 bg-purple-600 text-white text-sm font-medium rounded-lg hover:bg-purple-700 transition-colors flex items-center gap-2"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
          PDF herunterladen
        </button>
      </div>

      {/* Recent Activity */}
      {state.commandBarHistory.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Letzte Aktivitaeten</h2>
          <div className="bg-white rounded-xl border border-gray-200 divide-y divide-gray-100">
            {state.commandBarHistory.slice(0, 5).map(entry => (
              <div key={entry.id} className="flex items-center gap-4 px-4 py-3">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center ${entry.success ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600'}`}>
                  {entry.success ? <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>
                    : <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>}
                </div>
                <div className="flex-1">
                  <p className="text-sm font-medium text-gray-900">{entry.query}</p>
                  <p className="text-xs text-gray-500">{new Date(entry.timestamp).toLocaleString('de-DE')}</p>
                </div>
                <span className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded-full">{entry.type}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
