'use client'

import React, { useState } from 'react'
import { useSDK } from '@/lib/sdk'

// =============================================================================
// TYPES
// =============================================================================

interface SecurityItem {
  id: string
  title: string
  description: string
  type: 'vulnerability' | 'misconfiguration' | 'compliance' | 'hardening'
  severity: 'critical' | 'high' | 'medium' | 'low'
  status: 'open' | 'in-progress' | 'resolved' | 'accepted-risk'
  source: string
  cve: string | null
  cvss: number | null
  affectedAsset: string
  assignedTo: string | null
  createdAt: Date
  dueDate: Date | null
  remediation: string
}

// =============================================================================
// MOCK DATA
// =============================================================================

const mockItems: SecurityItem[] = [
  {
    id: 'sec-001',
    title: 'SQL Injection in Login-Modul',
    description: 'Unzureichende Validierung von Benutzereingaben ermoeglicht SQL Injection',
    type: 'vulnerability',
    severity: 'critical',
    status: 'in-progress',
    source: 'Penetrationstest',
    cve: 'CVE-2024-12345',
    cvss: 9.8,
    affectedAsset: 'auth-service',
    assignedTo: 'Entwicklung',
    createdAt: new Date('2024-01-15'),
    dueDate: new Date('2024-01-25'),
    remediation: 'Parameterisierte Queries verwenden, Input-Validierung implementieren',
  },
  {
    id: 'sec-002',
    title: 'Veraltete TLS-Version',
    description: 'Server unterstuetzt noch TLS 1.0 und 1.1',
    type: 'misconfiguration',
    severity: 'high',
    status: 'open',
    source: 'Vulnerability Scanner',
    cve: null,
    cvss: 7.5,
    affectedAsset: 'web-server',
    assignedTo: null,
    createdAt: new Date('2024-01-18'),
    dueDate: new Date('2024-02-01'),
    remediation: 'TLS 1.2 als Minimum konfigurieren, TLS 1.3 bevorzugen',
  },
  {
    id: 'sec-003',
    title: 'Fehlende Content-Security-Policy',
    description: 'HTTP-Header CSP nicht konfiguriert',
    type: 'hardening',
    severity: 'medium',
    status: 'open',
    source: 'Security Audit',
    cve: null,
    cvss: 5.4,
    affectedAsset: 'website',
    assignedTo: 'DevOps',
    createdAt: new Date('2024-01-10'),
    dueDate: new Date('2024-02-15'),
    remediation: 'Strikte CSP-Header implementieren',
  },
  {
    id: 'sec-004',
    title: 'Unsichere Cookie-Konfiguration',
    description: 'Session-Cookies ohne Secure und HttpOnly Flags',
    type: 'misconfiguration',
    severity: 'medium',
    status: 'resolved',
    source: 'Code Review',
    cve: null,
    cvss: 5.3,
    affectedAsset: 'auth-service',
    assignedTo: 'Entwicklung',
    createdAt: new Date('2024-01-05'),
    dueDate: new Date('2024-01-15'),
    remediation: 'Cookie-Flags setzen: Secure, HttpOnly, SameSite',
  },
  {
    id: 'sec-005',
    title: 'Veraltete Abhaengigkeit lodash',
    description: 'Bekannte Schwachstelle in lodash < 4.17.21',
    type: 'vulnerability',
    severity: 'high',
    status: 'in-progress',
    source: 'SBOM Scan',
    cve: 'CVE-2021-23337',
    cvss: 7.2,
    affectedAsset: 'frontend-app',
    assignedTo: 'Entwicklung',
    createdAt: new Date('2024-01-20'),
    dueDate: new Date('2024-01-30'),
    remediation: 'Abhaengigkeit auf Version 4.17.21 oder hoeher aktualisieren',
  },
  {
    id: 'sec-006',
    title: 'Fehlende Verschluesselung at Rest',
    description: 'Datenbank-Backup ohne Verschluesselung',
    type: 'compliance',
    severity: 'high',
    status: 'accepted-risk',
    source: 'Compliance Audit',
    cve: null,
    cvss: null,
    affectedAsset: 'database-backup',
    assignedTo: 'IT Operations',
    createdAt: new Date('2024-01-08'),
    dueDate: null,
    remediation: 'Backup-Verschluesselung aktivieren (AES-256)',
  },
]

// =============================================================================
// COMPONENTS
// =============================================================================

function SecurityItemCard({ item }: { item: SecurityItem }) {
  const typeLabels = {
    vulnerability: 'Schwachstelle',
    misconfiguration: 'Fehlkonfiguration',
    compliance: 'Compliance',
    hardening: 'Haertung',
  }

  const typeColors = {
    vulnerability: 'bg-red-100 text-red-700',
    misconfiguration: 'bg-orange-100 text-orange-700',
    compliance: 'bg-purple-100 text-purple-700',
    hardening: 'bg-blue-100 text-blue-700',
  }

  const severityColors = {
    critical: 'bg-red-500 text-white',
    high: 'bg-orange-500 text-white',
    medium: 'bg-yellow-500 text-white',
    low: 'bg-green-500 text-white',
  }

  const statusColors = {
    open: 'bg-blue-100 text-blue-700',
    'in-progress': 'bg-yellow-100 text-yellow-700',
    resolved: 'bg-green-100 text-green-700',
    'accepted-risk': 'bg-gray-100 text-gray-600',
  }

  const statusLabels = {
    open: 'Offen',
    'in-progress': 'In Bearbeitung',
    resolved: 'Behoben',
    'accepted-risk': 'Akzeptiert',
  }

  const isOverdue = item.dueDate && item.dueDate < new Date() && item.status !== 'resolved'

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      item.severity === 'critical' && item.status !== 'resolved' ? 'border-red-300' :
      isOverdue ? 'border-orange-300' :
      item.status === 'resolved' ? 'border-green-200' : 'border-gray-200'
    }`}>
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-2">
            <span className={`px-2 py-1 text-xs rounded-full ${severityColors[item.severity]}`}>
              {item.severity.toUpperCase()}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${typeColors[item.type]}`}>
              {typeLabels[item.type]}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${statusColors[item.status]}`}>
              {statusLabels[item.status]}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{item.title}</h3>
          <p className="text-sm text-gray-500 mt-1">{item.description}</p>
        </div>
      </div>

      <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
        <div>
          <span className="text-gray-500">Betroffenes Asset: </span>
          <span className="font-medium text-gray-700">{item.affectedAsset}</span>
        </div>
        <div>
          <span className="text-gray-500">Quelle: </span>
          <span className="font-medium text-gray-700">{item.source}</span>
        </div>
        {item.cve && (
          <div>
            <span className="text-gray-500">CVE: </span>
            <span className="font-mono text-gray-700">{item.cve}</span>
          </div>
        )}
        {item.cvss && (
          <div>
            <span className="text-gray-500">CVSS: </span>
            <span className={`font-bold ${
              item.cvss >= 9 ? 'text-red-600' :
              item.cvss >= 7 ? 'text-orange-600' :
              item.cvss >= 4 ? 'text-yellow-600' : 'text-green-600'
            }`}>{item.cvss}</span>
          </div>
        )}
        <div>
          <span className="text-gray-500">Zugewiesen: </span>
          <span className="font-medium text-gray-700">{item.assignedTo || 'Nicht zugewiesen'}</span>
        </div>
        {item.dueDate && (
          <div className={isOverdue ? 'text-red-600' : ''}>
            <span className="text-gray-500">Frist: </span>
            <span className="font-medium">
              {item.dueDate.toLocaleDateString('de-DE')}
              {isOverdue && ' (ueberfaellig)'}
            </span>
          </div>
        )}
      </div>

      <div className="mt-4 p-3 bg-gray-50 rounded-lg">
        <span className="text-sm text-gray-500">Empfohlene Massnahme: </span>
        <span className="text-sm text-gray-700">{item.remediation}</span>
      </div>

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
        <span className="text-xs text-gray-500">
          Erstellt: {item.createdAt.toLocaleDateString('de-DE')}
        </span>
        {item.status !== 'resolved' && (
          <div className="flex items-center gap-2">
            <button className="px-3 py-1 text-sm text-purple-600 hover:bg-purple-50 rounded-lg transition-colors">
              Bearbeiten
            </button>
            <button className="px-3 py-1 text-sm bg-green-50 text-green-700 hover:bg-green-100 rounded-lg transition-colors">
              Als behoben markieren
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

// =============================================================================
// MAIN PAGE
// =============================================================================

export default function SecurityBacklogPage() {
  const { state } = useSDK()
  const [items] = useState<SecurityItem[]>(mockItems)
  const [filter, setFilter] = useState<string>('all')

  const filteredItems = filter === 'all'
    ? items
    : items.filter(i => i.severity === filter || i.status === filter || i.type === filter)

  const openItems = items.filter(i => i.status === 'open').length
  const criticalCount = items.filter(i => i.severity === 'critical' && i.status !== 'resolved').length
  const highCount = items.filter(i => i.severity === 'high' && i.status !== 'resolved').length
  const overdueCount = items.filter(i =>
    i.dueDate && i.dueDate < new Date() && i.status !== 'resolved'
  ).length

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Security Backlog</h1>
          <p className="mt-1 text-gray-500">
            Verwalten Sie Sicherheitsbefunde und verfolgen Sie deren Behebung
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
            SBOM importieren
          </button>
          <button className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-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="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
            Befund erfassen
          </button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <div className="text-sm text-gray-500">Offen</div>
          <div className="text-3xl font-bold text-gray-900">{openItems}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-6">
          <div className="text-sm text-red-600">Kritisch</div>
          <div className="text-3xl font-bold text-red-600">{criticalCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-orange-200 p-6">
          <div className="text-sm text-orange-600">Hoch</div>
          <div className="text-3xl font-bold text-orange-600">{highCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-yellow-200 p-6">
          <div className="text-sm text-yellow-600">Ueberfaellig</div>
          <div className="text-3xl font-bold text-yellow-600">{overdueCount}</div>
        </div>
      </div>

      {/* Critical Alert */}
      {criticalCount > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-center gap-4">
          <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
            <svg className="w-5 h-5 text-red-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>
            <h4 className="font-medium text-red-800">{criticalCount} kritische Schwachstelle(n) erfordern sofortige Aufmerksamkeit</h4>
            <p className="text-sm text-red-600">
              Diese Befunde haben ein CVSS von 9.0 oder hoeher und sollten priorisiert werden.
            </p>
          </div>
        </div>
      )}

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'open', 'in-progress', 'critical', 'high', 'vulnerability', 'misconfiguration'].map(f => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`px-3 py-1 text-sm rounded-full transition-colors ${
              filter === f
                ? 'bg-purple-600 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            {f === 'all' ? 'Alle' :
             f === 'open' ? 'Offen' :
             f === 'in-progress' ? 'In Bearbeitung' :
             f === 'critical' ? 'Kritisch' :
             f === 'high' ? 'Hoch' :
             f === 'vulnerability' ? 'Schwachstellen' : 'Fehlkonfigurationen'}
          </button>
        ))}
      </div>

      {/* Items List */}
      <div className="space-y-4">
        {filteredItems
          .sort((a, b) => {
            // Sort by severity and status
            const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 }
            const statusOrder = { open: 0, 'in-progress': 1, 'accepted-risk': 2, resolved: 3 }
            const severityDiff = severityOrder[a.severity] - severityOrder[b.severity]
            if (severityDiff !== 0) return severityDiff
            return statusOrder[a.status] - statusOrder[b.status]
          })
          .map(item => (
            <SecurityItemCard key={item.id} item={item} />
          ))}
      </div>

      {filteredItems.length === 0 && (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <div className="w-16 h-16 mx-auto bg-green-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 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>
          <h3 className="text-lg font-semibold text-gray-900">Keine Befunde gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder fuehren Sie einen neuen Scan durch.</p>
        </div>
      )}
    </div>
  )
}
