'use client'

import React, { useState, useEffect, useMemo, useCallback } from 'react'
import { useSDK } from '@/lib/sdk'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import {
  Incident,
  IncidentSeverity,
  IncidentStatus,
  IncidentCategory,
  IncidentStatistics,
  INCIDENT_SEVERITY_INFO,
  INCIDENT_STATUS_INFO,
  INCIDENT_CATEGORY_INFO,
  getHoursUntil72hDeadline,
  is72hDeadlineExpired
} from '@/lib/sdk/incidents/types'
import { fetchSDKIncidentList, createMockIncidents, createMockStatistics } from '@/lib/sdk/incidents/api'

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

type TabId = 'overview' | 'active' | 'notification' | 'closed' | 'settings'

interface Tab {
  id: TabId
  label: string
  count?: number
  countColor?: string
}

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

function TabNavigation({
  tabs,
  activeTab,
  onTabChange
}: {
  tabs: Tab[]
  activeTab: TabId
  onTabChange: (tab: TabId) => void
}) {
  return (
    <div className="border-b border-gray-200">
      <nav className="flex gap-1 -mb-px" aria-label="Tabs">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => onTabChange(tab.id)}
            className={`
              px-4 py-3 text-sm font-medium border-b-2 transition-colors
              ${activeTab === tab.id
                ? 'border-purple-600 text-purple-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }
            `}
          >
            <span className="flex items-center gap-2">
              {tab.label}
              {tab.count !== undefined && tab.count > 0 && (
                <span className={`
                  px-2 py-0.5 text-xs rounded-full
                  ${tab.countColor || 'bg-gray-100 text-gray-600'}
                `}>
                  {tab.count}
                </span>
              )}
            </span>
          </button>
        ))}
      </nav>
    </div>
  )
}

function StatCard({
  label,
  value,
  color = 'gray',
  icon,
  trend
}: {
  label: string
  value: number | string
  color?: 'gray' | 'blue' | 'yellow' | 'red' | 'green' | 'purple' | 'orange'
  icon?: React.ReactNode
  trend?: { value: number; label: string }
}) {
  const colorClasses: Record<string, string> = {
    gray: 'border-gray-200 text-gray-900',
    blue: 'border-blue-200 text-blue-600',
    yellow: 'border-yellow-200 text-yellow-600',
    red: 'border-red-200 text-red-600',
    green: 'border-green-200 text-green-600',
    purple: 'border-purple-200 text-purple-600',
    orange: 'border-orange-200 text-orange-600'
  }

  return (
    <div className={`bg-white rounded-xl border ${colorClasses[color]} p-6`}>
      <div className="flex items-start justify-between">
        <div>
          <div className={`text-sm ${color === 'gray' ? 'text-gray-500' : ''}`}>
            {label}
          </div>
          <div className={`text-3xl font-bold mt-1 ${colorClasses[color].split(' ')[1]}`}>
            {value}
          </div>
          {trend && (
            <div className={`text-xs mt-1 ${trend.value >= 0 ? 'text-green-600' : 'text-red-600'}`}>
              {trend.value >= 0 ? '+' : ''}{trend.value} {trend.label}
            </div>
          )}
        </div>
        {icon && (
          <div className="w-10 h-10 rounded-lg flex items-center justify-center bg-gray-50">
            {icon}
          </div>
        )}
      </div>
    </div>
  )
}

function FilterBar({
  selectedSeverity,
  selectedStatus,
  selectedCategory,
  onSeverityChange,
  onStatusChange,
  onCategoryChange,
  onClear
}: {
  selectedSeverity: IncidentSeverity | 'all'
  selectedStatus: IncidentStatus | 'all'
  selectedCategory: IncidentCategory | 'all'
  onSeverityChange: (severity: IncidentSeverity | 'all') => void
  onStatusChange: (status: IncidentStatus | 'all') => void
  onCategoryChange: (category: IncidentCategory | 'all') => void
  onClear: () => void
}) {
  const hasFilters = selectedSeverity !== 'all' || selectedStatus !== 'all' || selectedCategory !== 'all'

  return (
    <div className="flex items-center gap-4 flex-wrap">
      <span className="text-sm text-gray-500">Filter:</span>

      {/* Severity Filter */}
      <select
        value={selectedSeverity}
        onChange={(e) => onSeverityChange(e.target.value as IncidentSeverity | 'all')}
        className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
      >
        <option value="all">Alle Schweregrade</option>
        {Object.entries(INCIDENT_SEVERITY_INFO).map(([severity, info]) => (
          <option key={severity} value={severity}>{info.label}</option>
        ))}
      </select>

      {/* Status Filter */}
      <select
        value={selectedStatus}
        onChange={(e) => onStatusChange(e.target.value as IncidentStatus | 'all')}
        className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
      >
        <option value="all">Alle Status</option>
        {Object.entries(INCIDENT_STATUS_INFO).map(([status, info]) => (
          <option key={status} value={status}>{info.label}</option>
        ))}
      </select>

      {/* Category Filter */}
      <select
        value={selectedCategory}
        onChange={(e) => onCategoryChange(e.target.value as IncidentCategory | 'all')}
        className="px-3 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
      >
        <option value="all">Alle Kategorien</option>
        {Object.entries(INCIDENT_CATEGORY_INFO).map(([cat, info]) => (
          <option key={cat} value={cat}>{info.label}</option>
        ))}
      </select>

      {/* Clear Filters */}
      {hasFilters && (
        <button
          onClick={onClear}
          className="px-3 py-1.5 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
        >
          Filter zuruecksetzen
        </button>
      )}
    </div>
  )
}

/**
 * 72h-Countdown-Anzeige mit visueller Farbkodierung
 * Gruen > 48h, Gelb > 24h, Orange > 12h, Rot < 12h oder abgelaufen
 */
function CountdownTimer({ incident }: { incident: Incident }) {
  const hoursRemaining = getHoursUntil72hDeadline(incident.detectedAt)
  const expired = is72hDeadlineExpired(incident.detectedAt)

  // Nicht relevant fuer abgeschlossene Vorfaelle
  if (incident.status === 'closed') return null

  // Bereits gemeldet
  if (incident.authorityNotification && (incident.authorityNotification.status === 'submitted' || incident.authorityNotification.status === 'acknowledged')) {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium bg-green-100 text-green-700 rounded-full">
        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
        </svg>
        Gemeldet
      </span>
    )
  }

  // Keine Meldepflicht festgestellt
  if (incident.riskAssessment && !incident.riskAssessment.notificationRequired) {
    return (
      <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium bg-gray-100 text-gray-600 rounded-full">
        Keine Meldepflicht
      </span>
    )
  }

  // Abgelaufen
  if (expired) {
    const overdueHours = Math.abs(hoursRemaining)
    return (
      <span className="inline-flex items-center gap-1 px-2 py-1 text-xs font-bold bg-red-100 text-red-700 rounded-full animate-pulse">
        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        {overdueHours.toFixed(0)}h ueberfaellig
      </span>
    )
  }

  // Farbkodierung: gruen > 48h, gelb > 24h, orange > 12h, rot < 12h
  let colorClass: string
  if (hoursRemaining > 48) {
    colorClass = 'bg-green-100 text-green-700'
  } else if (hoursRemaining > 24) {
    colorClass = 'bg-yellow-100 text-yellow-700'
  } else if (hoursRemaining > 12) {
    colorClass = 'bg-orange-100 text-orange-700'
  } else {
    colorClass = 'bg-red-100 text-red-700'
  }

  return (
    <span className={`inline-flex items-center gap-1 px-2 py-1 text-xs font-bold rounded-full ${colorClass}`}>
      <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      {hoursRemaining.toFixed(0)}h verbleibend
    </span>
  )
}

function Badge({ bgColor, color, label }: { bgColor: string; color: string; label: string }) {
  return <span className={`px-2 py-1 text-xs rounded-full ${bgColor} ${color}`}>{label}</span>
}

function IncidentCard({ incident, onClick }: { incident: Incident; onClick?: () => void }) {
  const severityInfo = INCIDENT_SEVERITY_INFO[incident.severity]
  const statusInfo = INCIDENT_STATUS_INFO[incident.status]
  const categoryInfo = INCIDENT_CATEGORY_INFO[incident.category]

  const expired = is72hDeadlineExpired(incident.detectedAt)
  const isNotified = incident.authorityNotification && (incident.authorityNotification.status === 'submitted' || incident.authorityNotification.status === 'acknowledged')

  const severityBorderColors: Record<IncidentSeverity, string> = {
    critical: 'border-red-300 hover:border-red-400',
    high: 'border-orange-300 hover:border-orange-400',
    medium: 'border-yellow-300 hover:border-yellow-400',
    low: 'border-green-200 hover:border-green-300'
  }

  const borderColor = incident.status === 'closed'
    ? 'border-green-200 hover:border-green-300'
    : expired && !isNotified
      ? 'border-red-400 hover:border-red-500'
      : severityBorderColors[incident.severity]

  const measuresCount = incident.measures.length
  const completedMeasures = incident.measures.filter(m => m.status === 'completed').length

  return (
    <div onClick={onClick} className="cursor-pointer">
      <div className={`
        bg-white rounded-xl border-2 p-6 hover:shadow-md transition-all cursor-pointer
        ${borderColor}
      `}>
        <div className="flex items-start justify-between">
          <div className="flex-1 min-w-0">
            {/* Header Badges */}
            <div className="flex items-center gap-2 mb-2 flex-wrap">
              <span className="text-xs text-gray-500 font-mono">
                {incident.referenceNumber}
              </span>
              <Badge bgColor={severityInfo.bgColor} color={severityInfo.color} label={severityInfo.label} />
              <Badge bgColor={categoryInfo.bgColor} color={categoryInfo.color} label={`${categoryInfo.icon} ${categoryInfo.label}`} />
              <Badge bgColor={statusInfo.bgColor} color={statusInfo.color} label={statusInfo.label} />
            </div>

            {/* Title */}
            <h3 className="text-lg font-semibold text-gray-900 truncate">
              {incident.title}
            </h3>
            <p className="text-sm text-gray-500 mt-1 line-clamp-2">
              {incident.description}
            </p>

            {/* 72h Countdown - prominent */}
            <div className="mt-3">
              <CountdownTimer incident={incident} />
            </div>
          </div>

          {/* Right Side - Key Numbers */}
          <div className="text-right ml-4 flex-shrink-0">
            <div className="text-sm text-gray-500">
              Betroffene
            </div>
            <div className="text-xl font-bold text-gray-900">
              {incident.estimatedAffectedPersons.toLocaleString('de-DE')}
            </div>
            <div className="text-xs text-gray-400 mt-1">
              {new Date(incident.detectedAt).toLocaleDateString('de-DE')}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
          <div className="flex items-center gap-4 text-sm text-gray-500">
            <span className="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="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 2m-6 9l2 2 4-4" />
              </svg>
              {completedMeasures}/{measuresCount} Massnahmen
            </span>
            <span className="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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              {incident.timeline.length} Eintraege
            </span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-500">
              {incident.assignedTo
                ? `Zugewiesen: ${incident.assignedTo}`
                : 'Nicht zugewiesen'
              }
            </span>
            {incident.status !== 'closed' ? (
              <span className="px-3 py-1 text-sm text-purple-600 hover:bg-purple-50 rounded-lg transition-colors">
                Bearbeiten
              </span>
            ) : (
              <span className="px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                Details
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// INCIDENT CREATE MODAL
// =============================================================================

function IncidentCreateModal({
  onClose,
  onSuccess
}: {
  onClose: () => void
  onSuccess: () => void
}) {
  const [title, setTitle] = useState('')
  const [category, setCategory] = useState('data_breach')
  const [severity, setSeverity] = useState('medium')
  const [description, setDescription] = useState('')
  const [detectedBy, setDetectedBy] = useState('')
  const [affectedSystems, setAffectedSystems] = useState('')
  const [estimatedAffectedPersons, setEstimatedAffectedPersons] = useState('0')
  const [isSaving, setIsSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSave = async () => {
    if (!title.trim()) {
      setError('Titel ist erforderlich.')
      return
    }
    setIsSaving(true)
    setError(null)
    try {
      const res = await fetch('/api/sdk/v1/incidents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title,
          category,
          severity,
          description,
          detectedBy,
          affectedSystems: affectedSystems.split(',').map(s => s.trim()).filter(Boolean),
          estimatedAffectedPersons: Number(estimatedAffectedPersons)
        })
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data.detail || data.message || `Fehler: ${res.status}`)
      }
      onSuccess()
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Unbekannter Fehler')
    } finally {
      setIsSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50"
        onClick={onClose}
      />
      {/* Modal */}
      <div className="relative bg-white rounded-xl shadow-2xl w-full max-w-lg mx-4 p-6 z-10 max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-xl font-semibold text-gray-900">Neuen Vorfall erfassen</h2>
          <button
            onClick={onClose}
            className="p-1 text-gray-400 hover:text-gray-600 rounded 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="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
            {error}
          </div>
        )}

        <div className="space-y-4">
          {/* Title */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Titel <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={title}
              onChange={e => setTitle(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm"
              placeholder="Kurze Beschreibung des Vorfalls"
            />
          </div>

          {/* Category */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Kategorie</label>
            <select
              value={category}
              onChange={e => setCategory(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm"
            >
              <option value="data_breach">Datenpanne</option>
              <option value="unauthorized_access">Unbefugter Zugriff</option>
              <option value="data_loss">Datenverlust</option>
              <option value="system_compromise">Systemkompromittierung</option>
              <option value="phishing">Phishing</option>
              <option value="ransomware">Ransomware</option>
              <option value="insider_threat">Insider-Bedrohung</option>
              <option value="physical_breach">Physischer Vorfall</option>
              <option value="other">Sonstiges</option>
            </select>
          </div>

          {/* Severity */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Schweregrad</label>
            <select
              value={severity}
              onChange={e => setSeverity(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm"
            >
              <option value="low">Niedrig (1)</option>
              <option value="medium">Mittel (2)</option>
              <option value="high">Hoch (3)</option>
              <option value="critical">Kritisch (4)</option>
            </select>
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
            <textarea
              value={description}
              onChange={e => setDescription(e.target.value)}
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm"
              placeholder="Detaillierte Beschreibung des Vorfalls"
            />
          </div>

          {/* Detected By */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Entdeckt von</label>
            <input
              type="text"
              value={detectedBy}
              onChange={e => setDetectedBy(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm"
              placeholder="Name / Team / System"
            />
          </div>

          {/* Affected Systems */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Betroffene Systeme
              <span className="ml-1 text-xs text-gray-400">(Kommagetrennt)</span>
            </label>
            <input
              type="text"
              value={affectedSystems}
              onChange={e => setAffectedSystems(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm"
              placeholder="z.B. CRM, E-Mail-Server, Datenbank"
            />
          </div>

          {/* Estimated Affected Persons */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Geschaetzte betroffene Personen</label>
            <input
              type="number"
              value={estimatedAffectedPersons}
              onChange={e => setEstimatedAffectedPersons(e.target.value)}
              min={0}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm"
            />
          </div>
        </div>

        {/* Buttons */}
        <div className="flex items-center justify-end gap-3 mt-6 pt-4 border-t border-gray-200">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
          >
            Abbrechen
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {isSaving && (
              <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
            )}
            Speichern
          </button>
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// INCIDENT DETAIL DRAWER
// =============================================================================

const STATUS_TRANSITIONS: Record<string, { label: string; nextStatus: string } | null> = {
  detected: { label: 'Bewertung starten', nextStatus: 'assessment' },
  assessment: { label: 'Eindaemmung starten', nextStatus: 'containment' },
  containment: { label: 'Meldepflicht pruefen', nextStatus: 'notification_required' },
  notification_required: { label: 'Gemeldet', nextStatus: 'notification_sent' },
  notification_sent: { label: 'Behebung starten', nextStatus: 'remediation' },
  remediation: { label: 'Abschliessen', nextStatus: 'closed' },
  closed: null
}

function IncidentDetailDrawer({
  incident,
  onClose,
  onStatusChange,
  onDeleted,
}: {
  incident: Incident
  onClose: () => void
  onStatusChange: () => void
  onDeleted?: () => void
}) {
  const [isChangingStatus, setIsChangingStatus] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)

  const handleDeleteIncident = async () => {
    if (!window.confirm(`Incident "${incident.title}" wirklich löschen?`)) return
    setIsDeleting(true)
    try {
      const res = await fetch(`/api/sdk/v1/incidents/${incident.id}`, { method: 'DELETE' })
      if (!res.ok) throw new Error(`Fehler: ${res.status}`)
      onDeleted ? onDeleted() : onClose()
    } catch (err) {
      console.error('Löschen fehlgeschlagen:', err)
      alert('Löschen fehlgeschlagen.')
    } finally {
      setIsDeleting(false)
    }
  }
  const severityInfo = INCIDENT_SEVERITY_INFO[incident.severity]
  const statusInfo = INCIDENT_STATUS_INFO[incident.status]
  const categoryInfo = INCIDENT_CATEGORY_INFO[incident.category]
  const transition = STATUS_TRANSITIONS[incident.status]

  const handleStatusChange = async (newStatus: string) => {
    setIsChangingStatus(true)
    try {
      const res = await fetch(`/api/sdk/v1/incidents/${incident.id}/status`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus })
      })
      if (!res.ok) {
        throw new Error(`Fehler: ${res.status}`)
      }
      onStatusChange()
    } catch (err) {
      console.error('Status-Aenderung fehlgeschlagen:', err)
    } finally {
      setIsChangingStatus(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/30"
        onClick={onClose}
      />
      {/* Drawer */}
      <div className="fixed right-0 top-0 h-full w-[600px] bg-white shadow-2xl z-10 overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 sticky top-0 bg-white z-10">
          <div className="flex items-center gap-3">
            <span className={`px-2 py-1 text-xs rounded-full ${severityInfo.bgColor} ${severityInfo.color}`}>
              {severityInfo.label}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${statusInfo.bgColor} ${statusInfo.color}`}>
              {statusInfo.label}
            </span>
          </div>
          <button
            onClick={onClose}
            className="p-1 text-gray-400 hover:text-gray-600 rounded 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="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="p-6 space-y-6">
          {/* Title */}
          <div>
            <p className="text-xs text-gray-400 font-mono mb-1">{incident.referenceNumber}</p>
            <h2 className="text-xl font-semibold text-gray-900">{incident.title}</h2>
          </div>

          {/* Status Transition */}
          {transition && (
            <div className="bg-purple-50 border border-purple-200 rounded-lg p-4">
              <p className="text-sm text-purple-700 mb-3">Naechster Schritt:</p>
              <button
                onClick={() => handleStatusChange(transition.nextStatus)}
                disabled={isChangingStatus}
                className="px-4 py-2 bg-purple-600 text-white text-sm rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {isChangingStatus && (
                  <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                )}
                {transition.label}
              </button>
            </div>
          )}

          {/* Details Grid */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <p className="text-xs text-gray-500 mb-1">Kategorie</p>
              <p className="text-sm font-medium text-gray-900">
                {categoryInfo.icon} {categoryInfo.label}
              </p>
            </div>
            <div>
              <p className="text-xs text-gray-500 mb-1">Schweregrad</p>
              <p className="text-sm font-medium text-gray-900">{severityInfo.label}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 mb-1">Status</p>
              <p className="text-sm font-medium text-gray-900">{statusInfo.label}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 mb-1">Entdeckt am</p>
              <p className="text-sm font-medium text-gray-900">
                {new Date(incident.detectedAt).toLocaleString('de-DE')}
              </p>
            </div>
            {incident.detectedBy && (
              <div>
                <p className="text-xs text-gray-500 mb-1">Entdeckt von</p>
                <p className="text-sm font-medium text-gray-900">{incident.detectedBy}</p>
              </div>
            )}
            {incident.assignedTo && (
              <div>
                <p className="text-xs text-gray-500 mb-1">Zugewiesen an</p>
                <p className="text-sm font-medium text-gray-900">{incident.assignedTo}</p>
              </div>
            )}
            <div>
              <p className="text-xs text-gray-500 mb-1">Betroffene Personen (geschaetzt)</p>
              <p className="text-sm font-medium text-gray-900">
                {incident.estimatedAffectedPersons.toLocaleString('de-DE')}
              </p>
            </div>
          </div>

          {/* Description */}
          {incident.description && (
            <div>
              <p className="text-xs text-gray-500 mb-2">Beschreibung</p>
              <p className="text-sm text-gray-700 leading-relaxed bg-gray-50 rounded-lg p-3">
                {incident.description}
              </p>
            </div>
          )}

          {/* Affected Systems */}
          {incident.affectedSystems && incident.affectedSystems.length > 0 && (
            <div>
              <p className="text-xs text-gray-500 mb-2">Betroffene Systeme</p>
              <div className="flex flex-wrap gap-2">
                {incident.affectedSystems.map((sys, idx) => (
                  <span key={idx} className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded-full">
                    {sys}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* 72h Countdown */}
          <div>
            <p className="text-xs text-gray-500 mb-2">72h-Meldefrist</p>
            <CountdownTimer incident={incident} />
          </div>

          {/* Delete */}
          <div className="pt-2 border-t border-gray-100">
            <button
              onClick={handleDeleteIncident}
              disabled={isDeleting}
              className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm transition-colors disabled:opacity-50"
            >
              {isDeleting ? 'Löschen...' : 'Löschen'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

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

export default function IncidentsPage() {
  const { state } = useSDK()
  const [activeTab, setActiveTab] = useState<TabId>('overview')
  const [incidents, setIncidents] = useState<Incident[]>([])
  const [statistics, setStatistics] = useState<IncidentStatistics | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [selectedIncident, setSelectedIncident] = useState<Incident | null>(null)

  // Filters
  const [selectedSeverity, setSelectedSeverity] = useState<IncidentSeverity | 'all'>('all')
  const [selectedStatus, setSelectedStatus] = useState<IncidentStatus | 'all'>('all')
  const [selectedCategory, setSelectedCategory] = useState<IncidentCategory | 'all'>('all')

  // Load data (extracted as useCallback so it can be called from modals)
  const loadData = useCallback(async () => {
    setIsLoading(true)
    try {
      const { incidents: loadedIncidents, statistics: loadedStats } = await fetchSDKIncidentList()
      setIncidents(loadedIncidents)
      setStatistics(loadedStats)
    } catch (error) {
      console.error('Fehler beim Laden der Incident-Daten:', error)
      // Fallback auf Mock-Daten
      setIncidents(createMockIncidents())
      setStatistics(createMockStatistics())
    } finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => {
    loadData()
  }, [loadData])

  // Calculate tab counts
  const tabCounts = useMemo(() => {
    return {
      active: incidents.filter(i =>
        i.status === 'detected' || i.status === 'assessment' ||
        i.status === 'containment' || i.status === 'remediation'
      ).length,
      notification: incidents.filter(i =>
        i.status === 'notification_required' || i.status === 'notification_sent' ||
        (i.authorityNotification !== null && i.authorityNotification.status === 'pending')
      ).length,
      closed: incidents.filter(i => i.status === 'closed').length,
      deadlineExpired: incidents.filter(i => {
        if (i.status === 'closed') return false
        if (i.authorityNotification && (i.authorityNotification.status === 'submitted' || i.authorityNotification.status === 'acknowledged')) return false
        if (i.riskAssessment && !i.riskAssessment.notificationRequired) return false
        return is72hDeadlineExpired(i.detectedAt)
      }).length,
      deadlineApproaching: incidents.filter(i => {
        if (i.status === 'closed') return false
        if (i.authorityNotification && (i.authorityNotification.status === 'submitted' || i.authorityNotification.status === 'acknowledged')) return false
        const hours = getHoursUntil72hDeadline(i.detectedAt)
        return hours > 0 && hours <= 24
      }).length
    }
  }, [incidents])

  // Filter incidents based on active tab and filters
  const filteredIncidents = useMemo(() => {
    let filtered = [...incidents]

    // Tab-based filtering
    if (activeTab === 'active') {
      filtered = filtered.filter(i =>
        i.status === 'detected' || i.status === 'assessment' ||
        i.status === 'containment' || i.status === 'remediation'
      )
    } else if (activeTab === 'notification') {
      filtered = filtered.filter(i =>
        i.status === 'notification_required' || i.status === 'notification_sent' ||
        (i.authorityNotification !== null && i.authorityNotification.status === 'pending')
      )
    } else if (activeTab === 'closed') {
      filtered = filtered.filter(i => i.status === 'closed')
    }

    // Severity filter
    if (selectedSeverity !== 'all') {
      filtered = filtered.filter(i => i.severity === selectedSeverity)
    }

    // Status filter
    if (selectedStatus !== 'all') {
      filtered = filtered.filter(i => i.status === selectedStatus)
    }

    // Category filter
    if (selectedCategory !== 'all') {
      filtered = filtered.filter(i => i.category === selectedCategory)
    }

    // Sort: most urgent first (overdue > deadline approaching > severity > detected time)
    const severityOrder: Record<IncidentSeverity, number> = { critical: 0, high: 1, medium: 2, low: 3 }
    return filtered.sort((a, b) => {
      // Closed always at the end
      if (a.status === 'closed' !== (b.status === 'closed')) return a.status === 'closed' ? 1 : -1

      // Overdue first
      const aExpired = is72hDeadlineExpired(a.detectedAt)
      const bExpired = is72hDeadlineExpired(b.detectedAt)
      if (aExpired !== bExpired) return aExpired ? -1 : 1

      // Then by severity
      if (severityOrder[a.severity] !== severityOrder[b.severity]) {
        return severityOrder[a.severity] - severityOrder[b.severity]
      }

      // Then by deadline urgency
      return getHoursUntil72hDeadline(a.detectedAt) - getHoursUntil72hDeadline(b.detectedAt)
    })
  }, [incidents, activeTab, selectedSeverity, selectedStatus, selectedCategory])

  const tabs: Tab[] = [
    { id: 'overview', label: 'Uebersicht' },
    { id: 'active', label: 'Aktiv', count: tabCounts.active, countColor: 'bg-orange-100 text-orange-600' },
    { id: 'notification', label: 'Meldepflichtig', count: tabCounts.notification, countColor: 'bg-red-100 text-red-600' },
    { id: 'closed', label: 'Abgeschlossen', count: tabCounts.closed, countColor: 'bg-green-100 text-green-600' },
    { id: 'settings', label: 'Einstellungen' }
  ]

  const stepInfo = STEP_EXPLANATIONS['incidents']

  const clearFilters = () => {
    setSelectedSeverity('all')
    setSelectedStatus('all')
    setSelectedCategory('all')
  }

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="incidents"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <button
          onClick={() => setShowCreateModal(true)}
          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>
          Vorfall melden
        </button>
      </StepHeader>

      {/* Tab Navigation */}
      <TabNavigation
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
      />

      {/* Loading State */}
      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <svg className="animate-spin w-8 h-8 text-purple-600" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
          </svg>
        </div>
      ) : activeTab === 'settings' ? (
        /* Settings Tab */
        <div className="bg-white rounded-xl border border-gray-200 p-8 text-center">
          <div className="w-16 h-16 mx-auto bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Einstellungen</h3>
          <p className="mt-2 text-gray-500">
            Incident-Management-Einstellungen, Eskalationswege und Meldevorlagen
            werden in einer spaeteren Version verfuegbar sein.
          </p>
        </div>
      ) : (
        <>
          {/* Statistics (Overview Tab) */}
          {activeTab === 'overview' && statistics && (
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <StatCard
                label="Gesamt Vorfaelle"
                value={statistics.totalIncidents}
                color="gray"
              />
              <StatCard
                label="Offene Vorfaelle"
                value={statistics.openIncidents}
                color="orange"
              />
              <StatCard
                label="Meldungen ausstehend"
                value={statistics.notificationsPending}
                color={statistics.notificationsPending > 0 ? 'red' : 'green'}
              />
              <StatCard
                label="Durchschn. Reaktionszeit"
                value={`${statistics.averageResponseTimeHours}h`}
                color="purple"
              />
            </div>
          )}

          {/* Critical Alert: 72h deadline approaching or expired */}
          {(tabCounts.deadlineExpired > 0 || tabCounts.deadlineApproaching > 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 flex-shrink-0">
                <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 className="flex-1">
                <h4 className="font-medium text-red-800">
                  {tabCounts.deadlineExpired > 0
                    ? `Achtung: ${tabCounts.deadlineExpired} ueberfaellige Meldung(en) - 72-Stunden-Frist ueberschritten!`
                    : `Warnung: ${tabCounts.deadlineApproaching} Meldung(en) mit ablaufender 72-Stunden-Frist`
                  }
                </h4>
                <p className="text-sm text-red-600">
                  {tabCounts.deadlineExpired > 0
                    ? 'Die gesetzliche Meldefrist nach Art. 33 DSGVO ist abgelaufen. Handeln Sie umgehend, um Bussgelder zu vermeiden. Verspaetete Meldungen muessen begruendet werden.'
                    : 'Die 72-Stunden-Meldefrist nach Art. 33 DSGVO laeuft in Kuerze ab. Fuehren Sie eine Risikobewertung durch und entscheiden Sie ueber die Meldepflicht.'
                  }
                </p>
              </div>
              <button
                onClick={() => {
                  setActiveTab('active')
                  setSelectedStatus('all')
                }}
                className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors text-sm font-medium"
              >
                Anzeigen
              </button>
            </div>
          )}

          {/* Info Box (Overview Tab) */}
          {activeTab === 'overview' && (
            <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
              <div className="flex items-start gap-3">
                <svg className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <div>
                  <h4 className="font-medium text-blue-800">Art. 33/34 DSGVO - 72-Stunden-Meldepflicht</h4>
                  <p className="text-sm text-blue-600 mt-1">
                    Nach Art. 33 DSGVO muessen Datenschutzverletzungen innerhalb von 72 Stunden
                    an die zustaendige Aufsichtsbehoerde gemeldet werden, sofern ein Risiko fuer
                    die Rechte und Freiheiten der betroffenen Personen besteht. Bei hohem Risiko
                    muessen gemaess Art. 34 DSGVO auch die betroffenen Personen benachrichtigt werden.
                    Alle Vorfaelle sind unabhaengig von der Meldepflicht zu dokumentieren (Art. 33 Abs. 5).
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Filters */}
          <FilterBar
            selectedSeverity={selectedSeverity}
            selectedStatus={selectedStatus}
            selectedCategory={selectedCategory}
            onSeverityChange={setSelectedSeverity}
            onStatusChange={setSelectedStatus}
            onCategoryChange={setSelectedCategory}
            onClear={clearFilters}
          />

          {/* Incidents List */}
          <div className="space-y-4">
            {filteredIncidents.map(incident => (
              <IncidentCard
                key={incident.id}
                incident={incident}
                onClick={() => setSelectedIncident(incident)}
              />
            ))}
          </div>

          {/* Empty State */}
          {filteredIncidents.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-gray-100 rounded-full flex items-center justify-center mb-4">
                <svg className="w-8 h-8 text-gray-400" 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 Vorfaelle gefunden</h3>
              <p className="mt-2 text-gray-500">
                {selectedSeverity !== 'all' || selectedStatus !== 'all' || selectedCategory !== 'all'
                  ? 'Passen Sie die Filter an oder'
                  : 'Es sind noch keine Vorfaelle erfasst worden.'
                }
              </p>
              {(selectedSeverity !== 'all' || selectedStatus !== 'all' || selectedCategory !== 'all') ? (
                <button
                  onClick={clearFilters}
                  className="mt-4 px-4 py-2 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors"
                >
                  Filter zuruecksetzen
                </button>
              ) : (
                <button
                  onClick={() => setShowCreateModal(true)}
                  className="mt-4 inline-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>
                  Ersten Vorfall erfassen
                </button>
              )}
            </div>
          )}
        </>
      )}

      {/* Create Modal */}
      {showCreateModal && (
        <IncidentCreateModal
          onClose={() => setShowCreateModal(false)}
          onSuccess={() => { setShowCreateModal(false); loadData() }}
        />
      )}

      {/* Detail Drawer */}
      {selectedIncident && (
        <IncidentDetailDrawer
          incident={selectedIncident}
          onClose={() => setSelectedIncident(null)}
          onStatusChange={() => { setSelectedIncident(null); loadData() }}
          onDeleted={() => { setSelectedIncident(null); loadData() }}
        />
      )}
    </div>
  )
}
