'use client'

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

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

interface Escalation {
  id: string
  title: string
  description: string
  type: 'data-breach' | 'dsr-overdue' | 'audit-finding' | 'compliance-gap' | 'security-incident'
  severity: 'critical' | 'high' | 'medium' | 'low'
  status: 'open' | 'in-progress' | 'resolved' | 'escalated'
  createdAt: Date
  deadline: Date | null
  assignedTo: string
  escalatedTo: string | null
  relatedItems: string[]
  actions: EscalationAction[]
}

interface EscalationAction {
  id: string
  action: string
  performedBy: string
  performedAt: Date
}

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

const mockEscalations: Escalation[] = [
  {
    id: 'esc-001',
    title: 'Potenzielle Datenpanne - Kundendaten',
    description: 'Unberechtigter Zugriff auf Kundendatenbank festgestellt',
    type: 'data-breach',
    severity: 'critical',
    status: 'escalated',
    createdAt: new Date('2024-01-22'),
    deadline: new Date('2024-01-25'),
    assignedTo: 'IT Security',
    escalatedTo: 'CISO',
    relatedItems: ['INC-2024-001'],
    actions: [
      { id: 'a1', action: 'Incident erkannt und gemeldet', performedBy: 'SOC Team', performedAt: new Date('2024-01-22T08:00:00') },
      { id: 'a2', action: 'An CISO eskaliert', performedBy: 'IT Security', performedAt: new Date('2024-01-22T09:30:00') },
    ],
  },
  {
    id: 'esc-002',
    title: 'DSR-Anfrage ueberfaellig',
    description: 'Auskunftsanfrage von Max Mustermann ueberschreitet 30-Tage-Frist',
    type: 'dsr-overdue',
    severity: 'high',
    status: 'in-progress',
    createdAt: new Date('2024-01-20'),
    deadline: new Date('2024-01-23'),
    assignedTo: 'DSB Mueller',
    escalatedTo: null,
    relatedItems: ['DSR-001'],
    actions: [
      { id: 'a1', action: 'Automatische Eskalation bei Fristueberschreitung', performedBy: 'System', performedAt: new Date('2024-01-20') },
    ],
  },
  {
    id: 'esc-003',
    title: 'Kritische Audit-Feststellung',
    description: 'Fehlende Auftragsverarbeitungsvertraege mit Cloud-Providern',
    type: 'audit-finding',
    severity: 'high',
    status: 'in-progress',
    createdAt: new Date('2024-01-15'),
    deadline: new Date('2024-02-15'),
    assignedTo: 'Rechtsabteilung',
    escalatedTo: null,
    relatedItems: ['AUDIT-2024-Q1-003'],
    actions: [
      { id: 'a1', action: 'Feststellung dokumentiert', performedBy: 'Auditor', performedAt: new Date('2024-01-15') },
      { id: 'a2', action: 'An Rechtsabteilung zugewiesen', performedBy: 'DSB Mueller', performedAt: new Date('2024-01-16') },
    ],
  },
  {
    id: 'esc-004',
    title: 'AI Act Compliance-Luecke',
    description: 'Hochrisiko-KI-System ohne Risikomanagementsystem',
    type: 'compliance-gap',
    severity: 'high',
    status: 'open',
    createdAt: new Date('2024-01-18'),
    deadline: new Date('2024-03-01'),
    assignedTo: 'KI-Compliance Team',
    escalatedTo: null,
    relatedItems: ['AI-SYS-002'],
    actions: [],
  },
  {
    id: 'esc-005',
    title: 'Sicherheitsluecke in Anwendung',
    description: 'Kritische CVE in verwendeter Bibliothek entdeckt',
    type: 'security-incident',
    severity: 'medium',
    status: 'resolved',
    createdAt: new Date('2024-01-10'),
    deadline: new Date('2024-01-17'),
    assignedTo: 'Entwicklung',
    escalatedTo: null,
    relatedItems: ['CVE-2024-12345'],
    actions: [
      { id: 'a1', action: 'CVE identifiziert', performedBy: 'Security Scanner', performedAt: new Date('2024-01-10') },
      { id: 'a2', action: 'Patch entwickelt', performedBy: 'Entwicklung', performedAt: new Date('2024-01-12') },
      { id: 'a3', action: 'Patch deployed', performedBy: 'DevOps', performedAt: new Date('2024-01-13') },
      { id: 'a4', action: 'Eskalation geschlossen', performedBy: 'IT Security', performedAt: new Date('2024-01-14') },
    ],
  },
]

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

function EscalationCard({ escalation }: { escalation: Escalation }) {
  const [expanded, setExpanded] = useState(false)

  const typeLabels = {
    'data-breach': 'Datenpanne',
    'dsr-overdue': 'DSR ueberfaellig',
    'audit-finding': 'Audit-Feststellung',
    'compliance-gap': 'Compliance-Luecke',
    'security-incident': 'Sicherheitsvorfall',
  }

  const typeColors = {
    'data-breach': 'bg-red-100 text-red-700',
    'dsr-overdue': 'bg-orange-100 text-orange-700',
    'audit-finding': 'bg-yellow-100 text-yellow-700',
    'compliance-gap': 'bg-purple-100 text-purple-700',
    'security-incident': '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',
    escalated: 'bg-red-100 text-red-700',
  }

  const statusLabels = {
    open: 'Offen',
    'in-progress': 'In Bearbeitung',
    resolved: 'Geloest',
    escalated: 'Eskaliert',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      escalation.severity === 'critical' ? 'border-red-300' :
      escalation.severity === 'high' ? 'border-orange-300' :
      escalation.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[escalation.severity]}`}>
              {escalation.severity.toUpperCase()}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${typeColors[escalation.type]}`}>
              {typeLabels[escalation.type]}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${statusColors[escalation.status]}`}>
              {statusLabels[escalation.status]}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{escalation.title}</h3>
          <p className="text-sm text-gray-500 mt-1">{escalation.description}</p>
        </div>
      </div>

      <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
        <div>
          <span className="text-gray-500">Zugewiesen: </span>
          <span className="font-medium text-gray-700">{escalation.assignedTo}</span>
        </div>
        {escalation.escalatedTo && (
          <div>
            <span className="text-gray-500">Eskaliert an: </span>
            <span className="font-medium text-red-600">{escalation.escalatedTo}</span>
          </div>
        )}
        {escalation.deadline && (
          <div>
            <span className="text-gray-500">Frist: </span>
            <span className="font-medium text-gray-700">{escalation.deadline.toLocaleDateString('de-DE')}</span>
          </div>
        )}
        <div>
          <span className="text-gray-500">Erstellt: </span>
          <span className="font-medium text-gray-700">{escalation.createdAt.toLocaleDateString('de-DE')}</span>
        </div>
      </div>

      {escalation.relatedItems.length > 0 && (
        <div className="mt-3 flex items-center gap-2">
          <span className="text-sm text-gray-500">Verknuepft:</span>
          {escalation.relatedItems.map(item => (
            <span key={item} className="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded font-mono">
              {item}
            </span>
          ))}
        </div>
      )}

      {escalation.actions.length > 0 && (
        <div className="mt-4">
          <button
            onClick={() => setExpanded(!expanded)}
            className="text-sm text-purple-600 hover:text-purple-700 flex items-center gap-1"
          >
            <span>{expanded ? 'Verlauf ausblenden' : `Verlauf anzeigen (${escalation.actions.length})`}</span>
            <svg className={`w-4 h-4 transition-transform ${expanded ? '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>
          </button>
          {expanded && (
            <div className="mt-3 space-y-2">
              {escalation.actions.map(action => (
                <div key={action.id} className="flex items-start gap-3 text-sm p-2 bg-gray-50 rounded-lg">
                  <div className="w-2 h-2 bg-purple-500 rounded-full mt-1.5" />
                  <div className="flex-1">
                    <p className="text-gray-700">{action.action}</p>
                    <p className="text-gray-500 text-xs">
                      {action.performedBy} - {action.performedAt.toLocaleString('de-DE')}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
        <span className="text-xs text-gray-500">{escalation.id}</span>
        {escalation.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">
              Aktion hinzufuegen
            </button>
            {escalation.status !== 'escalated' && (
              <button className="px-3 py-1 text-sm text-orange-600 hover:bg-orange-50 rounded-lg transition-colors">
                Eskalieren
              </button>
            )}
            <button className="px-3 py-1 text-sm bg-green-50 text-green-700 hover:bg-green-100 rounded-lg transition-colors">
              Loesen
            </button>
          </div>
        )}
      </div>
    </div>
  )
}

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

export default function EscalationsPage() {
  const { state } = useSDK()
  const [escalations] = useState<Escalation[]>(mockEscalations)
  const [filter, setFilter] = useState<string>('all')

  const filteredEscalations = filter === 'all'
    ? escalations
    : escalations.filter(e => e.type === filter || e.status === filter || e.severity === filter)

  const openCount = escalations.filter(e => e.status === 'open').length
  const criticalCount = escalations.filter(e => e.severity === 'critical' && e.status !== 'resolved').length
  const escalatedCount = escalations.filter(e => e.status === 'escalated').length

  const stepInfo = STEP_EXPLANATIONS['escalations']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="escalations"
        title={stepInfo.title}
        description={stepInfo.description}
        explanation={stepInfo.explanation}
        tips={stepInfo.tips}
      >
        <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>
          Eskalation erstellen
        </button>
      </StepHeader>

      {/* 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">Gesamt aktiv</div>
          <div className="text-3xl font-bold text-gray-900">
            {escalations.filter(e => e.status !== 'resolved').length}
          </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">Eskaliert</div>
          <div className="text-3xl font-bold text-orange-600">{escalatedCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Offen</div>
          <div className="text-3xl font-bold text-blue-600">{openCount}</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 Eskalation(en) erfordern sofortige Aufmerksamkeit</h4>
            <p className="text-sm text-red-600">Priorisieren Sie diese Vorfaelle zur Vermeidung von Schaeden.</p>
          </div>
        </div>
      )}

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'open', 'escalated', 'critical', 'data-breach', 'compliance-gap'].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 === 'escalated' ? 'Eskaliert' :
             f === 'critical' ? 'Kritisch' :
             f === 'data-breach' ? 'Datenpannen' : 'Compliance-Luecken'}
          </button>
        ))}
      </div>

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

      {filteredEscalations.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-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Eskalationen gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an.</p>
        </div>
      )}
    </div>
  )
}
