'use client'

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

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

interface Obligation {
  id: string
  title: string
  description: string
  source: string
  sourceArticle: string
  deadline: Date | null
  status: 'pending' | 'in-progress' | 'completed' | 'overdue'
  priority: 'critical' | 'high' | 'medium' | 'low'
  responsible: string
  linkedSystems: string[]
}

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

const mockObligations: Obligation[] = [
  {
    id: 'obl-1',
    title: 'Risikomanagementsystem implementieren',
    description: 'Ein Risikomanagementsystem fuer das Hochrisiko-KI-System muss implementiert werden.',
    source: 'AI Act',
    sourceArticle: 'Art. 9',
    deadline: new Date('2024-06-01'),
    status: 'in-progress',
    priority: 'critical',
    responsible: 'IT Security',
    linkedSystems: ['Bewerber-Screening'],
  },
  {
    id: 'obl-2',
    title: 'Technische Dokumentation erstellen',
    description: 'Umfassende technische Dokumentation fuer alle Hochrisiko-KI-Systeme.',
    source: 'AI Act',
    sourceArticle: 'Art. 11',
    deadline: new Date('2024-05-15'),
    status: 'pending',
    priority: 'high',
    responsible: 'Entwicklung',
    linkedSystems: ['Bewerber-Screening'],
  },
  {
    id: 'obl-3',
    title: 'Datenschutzerklaerung aktualisieren',
    description: 'Die Datenschutzerklaerung muss an die neuen KI-Verarbeitungen angepasst werden.',
    source: 'DSGVO',
    sourceArticle: 'Art. 13/14',
    deadline: new Date('2024-02-01'),
    status: 'overdue',
    priority: 'high',
    responsible: 'Datenschutz',
    linkedSystems: ['Kundenservice Chatbot', 'Empfehlungsalgorithmus'],
  },
  {
    id: 'obl-4',
    title: 'KI-Kennzeichnung implementieren',
    description: 'Nutzer muessen informiert werden, dass sie mit einem KI-System interagieren.',
    source: 'AI Act',
    sourceArticle: 'Art. 52',
    deadline: new Date('2024-03-01'),
    status: 'completed',
    priority: 'medium',
    responsible: 'UX Team',
    linkedSystems: ['Kundenservice Chatbot'],
  },
  {
    id: 'obl-5',
    title: 'Menschliche Aufsicht sicherstellen',
    description: 'Prozesse fuer menschliche Aufsicht bei automatisierten Entscheidungen.',
    source: 'AI Act',
    sourceArticle: 'Art. 14',
    deadline: new Date('2024-04-01'),
    status: 'pending',
    priority: 'critical',
    responsible: 'Operations',
    linkedSystems: ['Bewerber-Screening'],
  },
]

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

function ObligationCard({ obligation }: { obligation: Obligation }) {
  const priorityColors = {
    critical: 'bg-red-100 text-red-700',
    high: 'bg-orange-100 text-orange-700',
    medium: 'bg-yellow-100 text-yellow-700',
    low: 'bg-green-100 text-green-700',
  }

  const statusColors = {
    pending: 'bg-gray-100 text-gray-600 border-gray-200',
    'in-progress': 'bg-blue-100 text-blue-700 border-blue-200',
    completed: 'bg-green-100 text-green-700 border-green-200',
    overdue: 'bg-red-100 text-red-700 border-red-200',
  }

  const statusLabels = {
    pending: 'Ausstehend',
    'in-progress': 'In Bearbeitung',
    completed: 'Abgeschlossen',
    overdue: 'Ueberfaellig',
  }

  const daysUntilDeadline = obligation.deadline
    ? Math.ceil((obligation.deadline.getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24))
    : null

  return (
    <div className={`bg-white rounded-xl border-2 p-6 ${
      obligation.status === 'overdue' ? 'border-red-200' :
      obligation.status === 'completed' ? '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 ${priorityColors[obligation.priority]}`}>
              {obligation.priority === 'critical' ? 'Kritisch' :
               obligation.priority === 'high' ? 'Hoch' :
               obligation.priority === 'medium' ? 'Mittel' : 'Niedrig'}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${statusColors[obligation.status]}`}>
              {statusLabels[obligation.status]}
            </span>
            <span className="px-2 py-1 text-xs bg-purple-50 text-purple-700 rounded">
              {obligation.source} {obligation.sourceArticle}
            </span>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{obligation.title}</h3>
          <p className="text-sm text-gray-500 mt-1">{obligation.description}</p>
        </div>
      </div>

      <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
        <div>
          <span className="text-gray-500">Verantwortlich: </span>
          <span className="font-medium text-gray-700">{obligation.responsible}</span>
        </div>
        {obligation.deadline && (
          <div className={daysUntilDeadline && daysUntilDeadline < 0 ? 'text-red-600' : ''}>
            <span className="text-gray-500">Frist: </span>
            <span className="font-medium">
              {obligation.deadline.toLocaleDateString('de-DE')}
              {daysUntilDeadline !== null && (
                <span className="ml-2">
                  ({daysUntilDeadline < 0 ? `${Math.abs(daysUntilDeadline)} Tage ueberfaellig` : `${daysUntilDeadline} Tage`})
                </span>
              )}
            </span>
          </div>
        )}
      </div>

      {obligation.linkedSystems.length > 0 && (
        <div className="mt-3 flex items-center gap-2 flex-wrap">
          <span className="text-sm text-gray-500">Betroffene Systeme:</span>
          {obligation.linkedSystems.map(sys => (
            <span key={sys} className="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded">
              {sys}
            </span>
          ))}
        </div>
      )}

      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between">
        <button className="text-sm text-purple-600 hover:text-purple-700 font-medium">
          Details anzeigen
        </button>
        {obligation.status !== 'completed' && (
          <button className="px-4 py-2 text-sm bg-purple-50 text-purple-700 rounded-lg hover:bg-purple-100 transition-colors">
            Als erledigt markieren
          </button>
        )}
      </div>
    </div>
  )
}

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

export default function ObligationsPage() {
  const { state } = useSDK()
  const [obligations] = useState<Obligation[]>(mockObligations)
  const [filter, setFilter] = useState<string>('all')

  const filteredObligations = filter === 'all'
    ? obligations
    : obligations.filter(o => o.status === filter || o.priority === filter || o.source.toLowerCase().includes(filter))

  const pendingCount = obligations.filter(o => o.status === 'pending').length
  const inProgressCount = obligations.filter(o => o.status === 'in-progress').length
  const overdueCount = obligations.filter(o => o.status === 'overdue').length
  const completedCount = obligations.filter(o => o.status === 'completed').length

  const stepInfo = STEP_EXPLANATIONS['obligations']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="obligations"
        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>
          Pflicht hinzufuegen
        </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">Ausstehend</div>
          <div className="text-3xl font-bold text-gray-900">{pendingCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">In Bearbeitung</div>
          <div className="text-3xl font-bold text-blue-600">{inProgressCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-red-200 p-6">
          <div className="text-sm text-red-600">Ueberfaellig</div>
          <div className="text-3xl font-bold text-red-600">{overdueCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Abgeschlossen</div>
          <div className="text-3xl font-bold text-green-600">{completedCount}</div>
        </div>
      </div>

      {/* Urgent Alert */}
      {overdueCount > 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">Achtung: {overdueCount} ueberfaellige Pflicht(en)</h4>
            <p className="text-sm text-red-600">Diese Pflichten erfordern sofortige Aufmerksamkeit.</p>
          </div>
        </div>
      )}

      {/* Filter */}
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'overdue', 'pending', 'in-progress', 'completed', 'critical', 'ai'].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 === 'overdue' ? 'Ueberfaellig' :
             f === 'pending' ? 'Ausstehend' :
             f === 'in-progress' ? 'In Bearbeitung' :
             f === 'completed' ? 'Abgeschlossen' :
             f === 'critical' ? 'Kritisch' : 'AI Act'}
          </button>
        ))}
      </div>

      {/* Obligations List */}
      <div className="space-y-4">
        {filteredObligations
          .sort((a, b) => {
            // Sort by status priority: overdue > in-progress > pending > completed
            const statusOrder = { overdue: 0, 'in-progress': 1, pending: 2, completed: 3 }
            return statusOrder[a.status] - statusOrder[b.status]
          })
          .map(obligation => (
            <ObligationCard key={obligation.id} obligation={obligation} />
          ))}
      </div>

      {filteredObligations.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 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 2" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-gray-900">Keine Pflichten gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder fuegen Sie neue Pflichten hinzu.</p>
        </div>
      )}
    </div>
  )
}
