'use client'

/**
 * Security Dashboard - DevSecOps
 *
 * Security scan results, vulnerability tracking, and compliance status
 */

import { useEffect, useState, useCallback } from 'react'
import { PagePurpose } from '@/components/common/PagePurpose'
import { DevOpsPipelineSidebarResponsive } from '@/components/infrastructure/DevOpsPipelineSidebar'
import type { ToolStatus, Finding, SeveritySummary, HistoryItem, ScanType, MonitoringMetric, ActiveAlert } from './types'

import { SecurityOverviewTab } from './_components/SecurityOverviewTab'
import { FindingsTab } from './_components/FindingsTab'
import { ToolsTab } from './_components/ToolsTab'
import { HistoryTab } from './_components/HistoryTab'
import { MonitoringTab } from './_components/MonitoringTab'
import { SecurityDocsSection } from './_components/SecurityDocsSection'

const TOOL_DESCRIPTIONS: Record<string, { icon: string; desc: string }> = {
  gitleaks: { icon: '🔑', desc: 'Secrets Detection in Git History' },
  semgrep: { icon: '🔍', desc: 'Static Application Security Testing (SAST)' },
  bandit: { icon: '🐍', desc: 'Python Security Linter' },
  trivy: { icon: '🔒', desc: 'Container & Filesystem Vulnerability Scanner' },
  grype: { icon: '🐛', desc: 'Vulnerability Scanner for Dependencies' },
  syft: { icon: '📦', desc: 'SBOM Generator (CycloneDX/SPDX)' },
}

const TOOL_TO_SCAN_TYPE: Record<string, ScanType> = {
  gitleaks: 'secrets',
  semgrep: 'sast',
  bandit: 'sast',
  trivy: 'deps',
  grype: 'deps',
  syft: 'sbom',
}

const SCAN_TYPE_LABELS: Record<ScanType, string> = {
  secrets: 'Secrets (Gitleaks)',
  sast: 'SAST (Semgrep + Bandit)',
  deps: 'Dependencies (Trivy + Grype)',
  containers: 'Container',
  sbom: 'SBOM (Syft)',
  all: 'Full Scan',
}

export default function SecurityDashboardPage() {
  const [tools, setTools] = useState<ToolStatus[]>([])
  const [findings, setFindings] = useState<Finding[]>([])
  const [summary, setSummary] = useState<SeveritySummary>({ critical: 0, high: 0, medium: 0, low: 0, info: 0, total: 0 })
  const [history, setHistory] = useState<HistoryItem[]>([])
  const [loading, setLoading] = useState(true)
  const [scanning, setScanning] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState<'overview' | 'findings' | 'tools' | 'history' | 'monitoring'>('overview')
  const [monitoringMetrics, setMonitoringMetrics] = useState<MonitoringMetric[]>([])
  const [activeAlerts, setActiveAlerts] = useState<ActiveAlert[]>([])
  const [severityFilter, setSeverityFilter] = useState<string | null>(null)
  const [toolFilter, setToolFilter] = useState<string | null>(null)
  const [scanMessage, setScanMessage] = useState<string | null>(null)
  const [lastScanTime, setLastScanTime] = useState<string | null>(null)

  const fetchData = useCallback(async (showLoadingSpinner = false) => {
    if (showLoadingSpinner) setLoading(true)
    setError(null)
    try {
      const [toolsRes, findingsRes, summaryRes, historyRes] = await Promise.all([
        fetch('/api/v1/security/tools'), fetch('/api/v1/security/findings'),
        fetch('/api/v1/security/summary'), fetch('/api/v1/security/history'),
      ])
      if (toolsRes.ok) setTools(await toolsRes.json())
      if (findingsRes.ok) setFindings(await findingsRes.json())
      if (summaryRes.ok) setSummary(await summaryRes.json())
      if (historyRes.ok) setHistory(await historyRes.json())

      const [metricsRes, alertsRes] = await Promise.all([
        fetch('/api/v1/security/monitoring/metrics'), fetch('/api/v1/security/monitoring/alerts'),
      ])
      if (metricsRes.ok) {
        setMonitoringMetrics(await metricsRes.json())
      } else {
        setMonitoringMetrics([
          { name: 'API Latency', value: 45, unit: 'ms', status: 'ok', trend: 'stable' },
          { name: 'Auth Failures', value: 3, unit: '/h', status: 'ok', trend: 'down' },
          { name: 'Rate Limit Hits', value: 12, unit: '/h', status: 'warning', trend: 'up' },
          { name: 'Failed Logins', value: 0, unit: '/24h', status: 'ok', trend: 'stable' },
          { name: 'SSL Expiry', value: 45, unit: 'days', status: 'ok', trend: 'down' },
          { name: 'Open Ports', value: 8, unit: '', status: 'ok', trend: 'stable' },
        ])
      }
      if (alertsRes.ok) setActiveAlerts(await alertsRes.json())
      else setActiveAlerts([])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Verbindung zum Backend fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { fetchData(true) }, [])
  useEffect(() => {
    const interval = setInterval(() => fetchData(false), 60000)
    return () => clearInterval(interval)
  }, [])

  const runScan = async (scanType: ScanType) => {
    setScanning(scanType)
    setError(null)
    setScanMessage(`${SCAN_TYPE_LABELS[scanType]} wird gestartet...`)
    try {
      const response = await fetch(`/api/v1/security/scan/${scanType}`, { method: 'POST', headers: { 'Content-Type': 'application/json' } })
      if (!response.ok) throw new Error(`Scan fehlgeschlagen: ${response.status}`)
      setScanMessage(`${SCAN_TYPE_LABELS[scanType]} laeuft im Hintergrund. Ergebnisse werden in wenigen Sekunden aktualisiert.`)
      setLastScanTime(new Date().toLocaleTimeString('de-DE'))
      setTimeout(() => { fetchData(false); setScanMessage(null) }, 5000)
      setTimeout(() => fetchData(false), 15000)
      setTimeout(() => fetchData(false), 30000)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Scan fehlgeschlagen')
      setScanMessage(null)
    } finally {
      setScanning(null)
    }
  }

  const getSeverityBadge = (severity: string) => {
    const base = 'px-3 py-1 rounded-full text-xs font-semibold uppercase'
    switch (severity.toUpperCase()) {
      case 'CRITICAL': return `${base} bg-red-100 text-red-800`
      case 'HIGH': return `${base} bg-orange-100 text-orange-800`
      case 'MEDIUM': return `${base} bg-yellow-100 text-yellow-800`
      case 'LOW': return `${base} bg-green-100 text-green-800`
      default: return `${base} bg-blue-100 text-blue-800`
    }
  }

  const getStatusBadge = (installed: boolean) => installed
    ? 'px-2 py-1 rounded text-xs font-semibold bg-green-100 text-green-800'
    : 'px-2 py-1 rounded text-xs font-semibold bg-red-100 text-red-800'

  const status = summary.critical > 0 ? { label: 'Critical Issues', color: 'bg-red-100 text-red-800' }
    : summary.high > 0 ? { label: 'High Issues', color: 'bg-orange-100 text-orange-800' }
    : summary.medium > 0 ? { label: 'Warnings', color: 'bg-yellow-100 text-yellow-800' }
    : { label: 'Secure', color: 'bg-green-100 text-green-800' }

  return (
    <div>
      <PagePurpose
        title="Security Dashboard"
        purpose="DevSecOps Dashboard mit Echtzeit-Scan-Ergebnissen. Ueberwachen Sie Secrets, Schwachstellen und Abhaengigkeiten."
        audience={['DevOps', 'Security', 'Entwickler']}
        gdprArticles={['Art. 32 (Sicherheit der Verarbeitung)']}
        architecture={{ services: ['Gitleaks', 'Semgrep', 'Bandit', 'Trivy', 'Grype', 'Syft'], databases: ['JSON Reports'] }}
        relatedPages={[
          { name: 'SBOM', href: '/infrastructure/sbom', description: 'Software Bill of Materials' },
          { name: 'Middleware', href: '/infrastructure/middleware', description: 'API Gateway & Rate Limiting' },
          { name: 'Controls', href: '/sdk/controls', description: 'Security Controls' },
        ]}
        collapsible={true} defaultCollapsed={true}
      />
      <DevOpsPipelineSidebarResponsive currentTool="security" />

      {/* Header with Status */}
      <div className="bg-white rounded-xl border border-slate-200 p-6 mb-6">
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center gap-4">
            <h2 className="text-xl font-semibold text-slate-900">Security Status</h2>
            <span className={`px-3 py-1 rounded-full text-sm font-semibold ${status.color}`}>{status.label}</span>
          </div>
          <div className="flex items-center gap-3">
            <span className="flex items-center gap-2 text-sm text-slate-500">
              <span className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />Auto-Refresh aktiv
            </span>
            <button onClick={() => runScan('all')} disabled={scanning !== null}
              className={`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${scanning === 'all' ? 'bg-orange-200 text-orange-800' : 'bg-orange-600 text-white hover:bg-orange-700 disabled:opacity-50'}`}>
              {scanning === 'all' ? (<><div className="animate-spin rounded-full h-4 w-4 border-b-2 border-orange-700" /><span>Full Scan laeuft...</span></>) : 'Full Scan starten'}
            </button>
          </div>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
          {[
            { label: 'Critical', value: summary.critical, color: 'border-red-500', textColor: 'text-red-600' },
            { label: 'High', value: summary.high, color: 'border-orange-500', textColor: 'text-orange-600' },
            { label: 'Medium', value: summary.medium, color: 'border-yellow-500', textColor: 'text-yellow-600' },
            { label: 'Low', value: summary.low, color: 'border-green-500', textColor: 'text-green-600' },
            { label: 'Info', value: summary.info, color: 'border-blue-500', textColor: 'text-blue-600' },
            { label: 'Total', value: summary.total, color: 'border-slate-400', textColor: 'text-slate-700' },
          ].map((item) => (
            <div key={item.label} className={`border-l-4 ${item.color} bg-slate-50 rounded-r-lg p-4`}>
              <div className={`text-3xl font-bold ${item.textColor}`}>{item.value}</div>
              <div className="text-sm text-slate-600">{item.label}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Tabs */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden mb-6">
        <div className="flex border-b border-slate-200">
          {(['overview', 'findings', 'tools', 'history', 'monitoring'] as const).map(tab => (
            <button key={tab} onClick={() => setActiveTab(tab)}
              className={`px-6 py-3 text-sm font-medium transition-colors ${activeTab === tab ? 'bg-orange-50 text-orange-700 border-b-2 border-orange-600' : 'text-slate-600 hover:bg-slate-50'}`}>
              {tab === 'overview' && 'Uebersicht'}
              {tab === 'findings' && `Findings (${summary.total})`}
              {tab === 'tools' && 'Tools'}
              {tab === 'history' && 'Historie'}
              {tab === 'monitoring' && 'Monitoring'}
            </button>
          ))}
        </div>
        <div className="p-6">
          {scanMessage && (
            <div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg text-blue-700 flex items-center gap-3">
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600" />
              <div>
                <span className="font-medium">{scanMessage}</span>
                {lastScanTime && <span className="text-sm text-blue-500 ml-2">(gestartet um {lastScanTime})</span>}
              </div>
            </div>
          )}
          {error && <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg text-red-700">{error}</div>}
          {loading ? (
            <div className="flex justify-center py-12"><div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-600" /></div>
          ) : (
            <>
              {activeTab === 'overview' && <SecurityOverviewTab tools={tools} findings={findings} scanning={scanning} onRunScan={runScan} onShowAllFindings={() => setActiveTab('findings')} toolDescriptions={TOOL_DESCRIPTIONS} toolToScanType={TOOL_TO_SCAN_TYPE} getSeverityBadge={getSeverityBadge} getStatusBadge={getStatusBadge} />}
              {activeTab === 'findings' && <FindingsTab findings={findings} severityFilter={severityFilter} setSeverityFilter={setSeverityFilter} toolFilter={toolFilter} setToolFilter={setToolFilter} getSeverityBadge={getSeverityBadge} />}
              {activeTab === 'tools' && <ToolsTab tools={tools} scanning={scanning} onRunScan={runScan} toolDescriptions={TOOL_DESCRIPTIONS} toolToScanType={TOOL_TO_SCAN_TYPE} getStatusBadge={getStatusBadge} />}
              {activeTab === 'history' && <HistoryTab history={history} />}
              {activeTab === 'monitoring' && <MonitoringTab monitoringMetrics={monitoringMetrics} activeAlerts={activeAlerts} />}
            </>
          )}
        </div>
      </div>

      <SecurityDocsSection />
    </div>
  )
}
