'use client'

/**
 * SBOM (Software Bill of Materials) Admin Page
 *
 * Displays all infrastructure components, dependencies, and license information.
 */

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { PagePurpose } from '@/components/common/PagePurpose'
import { DevOpsPipelineSidebarResponsive } from '@/components/infrastructure/DevOpsPipelineSidebar'
import type { Component, SBOMData, CategoryType, InfoTabType } from './types'
import {
  INFRASTRUCTURE_COMPONENTS, SECURITY_TOOLS,
  PYTHON_PACKAGES, GO_MODULES, NODE_PACKAGES, UNITY_PACKAGES, CSHARP_PACKAGES,
} from './_components/sbom-data'

// =============================================================================
// Helpers
// =============================================================================

const getCategoryColor = (category?: string) => {
  const map: Record<string, string> = {
    database: 'bg-blue-100 text-blue-800', security: 'bg-purple-100 text-purple-800',
    'security-tool': 'bg-red-100 text-red-800', application: 'bg-green-100 text-green-800',
    communication: 'bg-yellow-100 text-yellow-800', storage: 'bg-orange-100 text-orange-800',
    search: 'bg-pink-100 text-pink-800', erp: 'bg-indigo-100 text-indigo-800',
    cache: 'bg-cyan-100 text-cyan-800', ai: 'bg-violet-100 text-violet-800',
    development: 'bg-gray-100 text-gray-800', cicd: 'bg-orange-100 text-orange-800',
    python: 'bg-emerald-100 text-emerald-800', go: 'bg-sky-100 text-sky-800',
    nodejs: 'bg-lime-100 text-lime-800', unity: 'bg-amber-100 text-amber-800',
    csharp: 'bg-fuchsia-100 text-fuchsia-800', game: 'bg-rose-100 text-rose-800',
    voice: 'bg-teal-100 text-teal-800', qa: 'bg-blue-100 text-blue-800',
  }
  return map[category || ''] || 'bg-slate-100 text-slate-800'
}

const getLicenseColor = (license?: string) => {
  if (!license) return 'bg-gray-100 text-gray-600'
  if (license.includes('MIT')) return 'bg-green-100 text-green-700'
  if (license.includes('Apache')) return 'bg-blue-100 text-blue-700'
  if (license.includes('BSD')) return 'bg-cyan-100 text-cyan-700'
  if (license.includes('GPL') || license.includes('LGPL')) return 'bg-orange-100 text-orange-700'
  return 'bg-gray-100 text-gray-600'
}

// =============================================================================
// Component
// =============================================================================

export default function SBOMPage() {
  const [sbomData, setSbomData] = useState<SBOMData | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeCategory, setActiveCategory] = useState<CategoryType>('all')
  const [searchTerm, setSearchTerm] = useState('')
  const [activeInfoTab, setActiveInfoTab] = useState<InfoTabType>('audit')
  const [showFullDocs, setShowFullDocs] = useState(false)

  useEffect(() => {
    (async () => {
      setLoading(true)
      try {
        const res = await fetch('/api/v1/security/sbom')
        if (res.ok) setSbomData(await res.json())
      } catch (error) {
        console.error('Failed to load SBOM:', error)
      } finally {
        setLoading(false)
      }
    })()
  }, [])

  const getFilteredComponents = (): Component[] => {
    let components: Component[]
    if (activeCategory === 'all') {
      components = [
        ...INFRASTRUCTURE_COMPONENTS, ...SECURITY_TOOLS, ...PYTHON_PACKAGES,
        ...GO_MODULES, ...NODE_PACKAGES, ...UNITY_PACKAGES, ...CSHARP_PACKAGES,
        ...(sbomData?.components || []).map(c => ({ ...c, category: 'python' })),
      ]
    } else if (activeCategory === 'infrastructure') components = INFRASTRUCTURE_COMPONENTS
    else if (activeCategory === 'security-tools') components = SECURITY_TOOLS
    else if (activeCategory === 'python') components = [...PYTHON_PACKAGES, ...(sbomData?.components || [])]
    else if (activeCategory === 'go') components = GO_MODULES
    else if (activeCategory === 'nodejs') components = NODE_PACKAGES
    else if (activeCategory === 'unity') components = UNITY_PACKAGES
    else if (activeCategory === 'csharp') components = CSHARP_PACKAGES
    else components = []

    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      components = components.filter(c =>
        c.name.toLowerCase().includes(term) || c.version.toLowerCase().includes(term) || (c.description?.toLowerCase().includes(term))
      )
    }
    return components
  }

  const stats = {
    totalInfra: INFRASTRUCTURE_COMPONENTS.length,
    totalSecurityTools: SECURITY_TOOLS.length,
    totalPython: PYTHON_PACKAGES.length + (sbomData?.components?.length || 0),
    totalGo: GO_MODULES.length,
    totalNode: NODE_PACKAGES.length,
    totalUnity: UNITY_PACKAGES.length,
    totalCsharp: CSHARP_PACKAGES.length,
    totalAll: INFRASTRUCTURE_COMPONENTS.length + SECURITY_TOOLS.length + PYTHON_PACKAGES.length + GO_MODULES.length + NODE_PACKAGES.length + UNITY_PACKAGES.length + CSHARP_PACKAGES.length + (sbomData?.components?.length || 0),
    databases: INFRASTRUCTURE_COMPONENTS.filter(c => c.category === 'database').length,
    game: INFRASTRUCTURE_COMPONENTS.filter(c => c.category === 'game').length,
  }

  const categories = [
    { id: 'all', name: 'Alle', count: stats.totalAll },
    { id: 'infrastructure', name: 'Infrastruktur', count: stats.totalInfra },
    { id: 'security-tools', name: 'Security Tools', count: stats.totalSecurityTools },
    { id: 'python', name: 'Python', count: stats.totalPython },
    { id: 'go', name: 'Go', count: stats.totalGo },
    { id: 'nodejs', name: 'Node.js', count: stats.totalNode },
    { id: 'unity', name: 'Unity', count: stats.totalUnity },
    { id: 'csharp', name: 'C#', count: stats.totalCsharp },
  ]

  const filteredComponents = getFilteredComponents()

  return (
    <div>
      <PagePurpose title="SBOM" purpose="Software Bill of Materials - Alle Komponenten & Abhaengigkeiten der Breakpilot-Plattform." audience={['DevOps', 'Compliance', 'Security', 'Auditoren']} gdprArticles={['Art. 32 (Sicherheit der Verarbeitung)']}
        architecture={{ services: ['Syft (SBOM Generator)', 'Trivy (CVE Scanner)'], databases: ['CycloneDX JSON'] }}
        relatedPages={[{ name: 'Security', href: '/infrastructure/security', description: 'DevSecOps Dashboard' }, { name: 'Controls', href: '/sdk/controls', description: 'Security Controls' }]}
        collapsible={true} defaultCollapsed={true} />

      <DevOpsPipelineSidebarResponsive currentTool="sbom" />

      <div className="mb-6 flex justify-end">
        <Link href="/infrastructure/sbom/wizard" className="flex items-center gap-2 px-4 py-2 rounded-lg font-medium bg-purple-100 text-purple-700 border border-purple-200 hover:bg-purple-200 transition-colors">
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" /></svg>
          Lern-Wizard
        </Link>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 lg:grid-cols-10 gap-4 mb-6">
        {[
          { value: stats.totalAll, label: 'Komponenten Total', color: 'text-slate-800' },
          { value: stats.totalInfra, label: 'Docker Services', color: 'text-purple-600' },
          { value: stats.totalSecurityTools, label: 'Security Tools', color: 'text-red-600' },
          { value: stats.totalPython, label: 'Python', color: 'text-emerald-600' },
          { value: stats.totalGo, label: 'Go', color: 'text-sky-600' },
          { value: stats.totalNode, label: 'Node.js', color: 'text-lime-600' },
          { value: stats.totalUnity, label: 'Unity', color: 'text-amber-600' },
          { value: stats.totalCsharp, label: 'C#', color: 'text-fuchsia-600' },
          { value: stats.databases, label: 'Datenbanken', color: 'text-blue-600' },
          { value: stats.game, label: 'Game', color: 'text-rose-600' },
        ].map((s) => (
          <div key={s.label} className="bg-white rounded-lg shadow p-4">
            <div className={`text-3xl font-bold ${s.color}`}>{s.value}</div>
            <div className="text-sm text-slate-500">{s.label}</div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow p-4 mb-6">
        <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
          <div className="flex flex-wrap gap-2">
            {categories.map((cat) => (
              <button key={cat.id} onClick={() => setActiveCategory(cat.id as CategoryType)}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${activeCategory === cat.id ? 'bg-orange-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'}`}>
                {cat.name} ({cat.count})
              </button>
            ))}
          </div>
          <div className="relative w-full md:w-64">
            <input type="text" placeholder="Suchen..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent" />
            <svg className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
        </div>
      </div>

      {/* SBOM Metadata */}
      {sbomData?.metadata && (
        <div className="bg-slate-50 rounded-lg p-4 mb-6 text-sm">
          <div className="flex flex-wrap gap-6">
            <div><span className="text-slate-500">Format:</span><span className="ml-2 font-medium">{sbomData.bomFormat} {sbomData.specVersion}</span></div>
            <div><span className="text-slate-500">Generiert:</span><span className="ml-2 font-medium">{sbomData.metadata.timestamp ? new Date(sbomData.metadata.timestamp).toLocaleString('de-DE') : '-'}</span></div>
            <div><span className="text-slate-500">Anwendung:</span><span className="ml-2 font-medium">{sbomData.metadata.component?.name} v{sbomData.metadata.component?.version}</span></div>
          </div>
        </div>
      )}

      {/* Components Table */}
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-orange-600"></div>
          <span className="ml-3 text-gray-600">Lade SBOM...</span>
        </div>
      ) : (
        <div className="bg-white rounded-lg shadow overflow-hidden">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Komponente</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Version</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kategorie</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider min-w-[300px]">Verwendungszweck</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Port</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Lizenz</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Source</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredComponents.map((component, idx) => {
                const licenseId = component.license || component.licenses?.[0]?.license?.id
                return (
                  <tr key={idx} className="hover:bg-gray-50">
                    <td className="px-4 py-4"><div className="text-sm font-medium text-gray-900">{component.name}</div></td>
                    <td className="px-4 py-4 whitespace-nowrap"><span className="text-sm font-mono text-gray-900">{component.version}</span></td>
                    <td className="px-4 py-4 whitespace-nowrap"><span className={`px-2 py-1 text-xs font-medium rounded ${getCategoryColor(component.category)}`}>{component.category || component.type}</span></td>
                    <td className="px-4 py-4">{component.description ? <div className="text-sm text-gray-600 leading-relaxed">{component.description}</div> : <span className="text-sm text-gray-400 italic">Keine Beschreibung</span>}</td>
                    <td className="px-4 py-4 whitespace-nowrap">{component.port ? <span className="text-sm font-mono text-gray-600">{component.port}</span> : <span className="text-sm text-gray-400">-</span>}</td>
                    <td className="px-4 py-4 whitespace-nowrap">{licenseId ? <span className={`px-2 py-1 text-xs font-medium rounded ${getLicenseColor(licenseId)}`}>{licenseId}</span> : <span className="text-sm text-gray-400">-</span>}</td>
                    <td className="px-4 py-4 whitespace-nowrap">{component.sourceUrl && component.sourceUrl !== '-' ? (
                      <a href={component.sourceUrl} target="_blank" rel="noopener noreferrer" className="text-orange-600 hover:text-orange-800 text-sm flex items-center gap-1">
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>GitHub
                      </a>
                    ) : <span className="text-sm text-gray-400">-</span>}</td>
                  </tr>
                )
              })}
            </tbody>
          </table>
          {filteredComponents.length === 0 && <div className="p-8 text-center text-gray-500">Keine Komponenten gefunden.</div>}
        </div>
      )}

      {/* Export Button */}
      <div className="mt-6 flex justify-end">
        <button onClick={() => {
          const data = JSON.stringify({ ...sbomData, infrastructure: INFRASTRUCTURE_COMPONENTS }, null, 2)
          const blob = new Blob([data], { type: 'application/json' })
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a'); a.href = url; a.download = `breakpilot-sbom-${new Date().toISOString().split('T')[0]}.json`; a.click()
        }} className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>
          SBOM exportieren (JSON)
        </button>
      </div>

      {/* Info Tabs Section */}
      <div className="mt-8">
        <div className="bg-white rounded-lg shadow">
          <div className="border-b border-gray-200">
            <nav className="flex -mb-px">
              {[{ id: 'audit' as const, label: 'Audit', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' }, { id: 'documentation' as const, label: 'Dokumentation', icon: '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' }].map((tab) => (
                <button key={tab.id} onClick={() => setActiveInfoTab(tab.id)}
                  className={`px-6 py-4 text-sm font-medium border-b-2 transition-colors ${activeInfoTab === tab.id ? 'border-orange-500 text-orange-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'}`}>
                  <span className="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={tab.icon} /></svg>
                    {tab.label}
                  </span>
                </button>
              ))}
            </nav>
          </div>
          <div className="p-6">
            {activeInfoTab === 'audit' && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="bg-slate-50 rounded-lg p-4">
                  <h3 className="text-lg font-semibold text-slate-800 mb-4">SBOM Status</h3>
                  <div className="space-y-3">
                    {['Letzte Generierung', 'Format', 'Komponenten', 'Transitive Deps'].map((label) => (
                      <div key={label} className="flex items-center justify-between">
                        <span className="text-sm text-slate-600">{label}</span>
                        <span className="flex items-center gap-2"><span className="w-2 h-2 rounded-full bg-green-500"></span><span className="text-sm font-medium">{label === 'Letzte Generierung' ? 'CI/CD' : label === 'Format' ? 'CycloneDX 1.5' : label === 'Komponenten' ? 'Alle erfasst' : 'Inkludiert'}</span></span>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="bg-slate-50 rounded-lg p-4">
                  <h3 className="text-lg font-semibold text-slate-800 mb-4">License Compliance</h3>
                  <div className="space-y-3">
                    {[{ label: 'Erlaubte Lizenzen', value: 'MIT, Apache, BSD', ok: true }, { label: 'Copyleft (GPL)', value: '0', ok: true }, { label: 'Unbekannte Lizenzen', value: '0', ok: true }, { label: 'Kommerzielle', value: 'Review erforderlich', ok: false }].map((item) => (
                      <div key={item.label} className="flex items-center justify-between">
                        <span className="text-sm text-slate-600">{item.label}</span>
                        <span className="flex items-center gap-2"><span className={`w-2 h-2 rounded-full ${item.ok ? 'bg-green-500' : 'bg-yellow-500'}`}></span><span className="text-sm font-medium">{item.value}</span></span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}
            {activeInfoTab === 'documentation' && (
              <div>
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-lg font-semibold text-slate-800">SBOM Dokumentation</h3>
                  <button onClick={() => setShowFullDocs(!showFullDocs)} className="px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 transition-colors flex items-center gap-2">
                    <svg className={`w-4 h-4 transition-transform ${showFullDocs ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
                    {showFullDocs ? 'Weniger anzeigen' : 'Vollstaendige Dokumentation'}
                  </button>
                </div>
                <div className="prose prose-slate max-w-none">
                  <p className="text-slate-600">Das SBOM-Modul generiert und analysiert die vollstaendige Komponentenliste aller Software-Abhaengigkeiten.</p>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
                    <div className="bg-blue-50 p-4 rounded-lg"><h4 className="font-medium text-blue-800 mb-2">Generator</h4><p className="text-sm text-blue-600">Syft (Primary), Trivy (Validation)</p></div>
                    <div className="bg-purple-50 p-4 rounded-lg"><h4 className="font-medium text-purple-800 mb-2">Format</h4><p className="text-sm text-purple-600">CycloneDX 1.5, SPDX</p></div>
                    <div className="bg-green-50 p-4 rounded-lg"><h4 className="font-medium text-green-800 mb-2">Retention</h4><p className="text-sm text-green-600">5 Jahre (Compliance)</p></div>
                  </div>
                </div>
                {showFullDocs && (
                  <div className="mt-6 bg-slate-50 rounded-lg p-6 border border-slate-200 prose prose-slate max-w-none overflow-auto max-h-[600px]">
                    <h2>Software Bill of Materials (SBOM)</h2>
                    <h3>1. Uebersicht</h3>
                    <p>Das SBOM-Modul generiert und analysiert die vollstaendige Komponentenliste aller Software-Abhaengigkeiten.</p>
                    <h3>2. Erfasste Komponenten</h3>
                    <table className="min-w-full"><thead><tr><th className="text-left">Typ</th><th className="text-left">Quelle</th><th className="text-left">Beispiele</th></tr></thead>
                      <tbody>
                        <tr><td>npm packages</td><td>package-lock.json</td><td>react, next, tailwindcss</td></tr>
                        <tr><td>Go modules</td><td>go.sum</td><td>gin, gorm, jwt-go</td></tr>
                        <tr><td>Python packages</td><td>requirements.txt</td><td>fastapi, pydantic, httpx</td></tr>
                        <tr><td>Container Images</td><td>Dockerfile</td><td>node:20-alpine, postgres:16</td></tr>
                      </tbody>
                    </table>
                    <h3>3. License Compliance</h3>
                    <table className="min-w-full"><thead><tr><th className="text-left">Kategorie</th><th className="text-left">Lizenzen</th><th className="text-left">Status</th></tr></thead>
                      <tbody>
                        <tr><td>Permissive</td><td>MIT, Apache 2.0, BSD, ISC</td><td className="text-green-600">OK</td></tr>
                        <tr><td>Weak Copyleft</td><td>LGPL, MPL</td><td className="text-yellow-600">Review</td></tr>
                        <tr><td>Strong Copyleft</td><td>GPL, AGPL</td><td className="text-red-600">Nicht erlaubt</td></tr>
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
