'use client'

import React, { useState, useEffect } 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[]
}

// =============================================================================
// 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>
  )
}

// =============================================================================
// HELPERS
// =============================================================================

function mapControlsToObligations(assessments: Array<{
  id: string
  title?: string
  domain?: string
  result?: {
    required_controls?: Array<{
      id: string
      title: string
      description: string
      gdpr_ref?: string
      effort?: string
    }>
    triggered_rules?: Array<{
      rule_code: string
      title: string
      severity: string
      gdpr_ref: string
    }>
    risk_level?: string
  }
}>): Obligation[] {
  const obligations: Obligation[] = []

  for (const assessment of assessments) {
    // Map triggered rules to obligations
    const rules = assessment.result?.triggered_rules || []
    for (const rule of rules) {
      const severity = rule.severity
      obligations.push({
        id: `${assessment.id}-${rule.rule_code}`,
        title: rule.title,
        description: `Aus Assessment: ${assessment.title || assessment.id.slice(0, 8)}`,
        source: rule.gdpr_ref?.includes('AI Act') ? 'AI Act' : 'DSGVO',
        sourceArticle: rule.gdpr_ref || '',
        deadline: null,
        status: 'pending',
        priority: severity === 'BLOCK' ? 'critical' : severity === 'WARN' ? 'high' : 'medium',
        responsible: 'Compliance Team',
        linkedSystems: assessment.title ? [assessment.title] : [],
      })
    }

    // Map required controls to obligations
    const controls = assessment.result?.required_controls || []
    for (const control of controls) {
      obligations.push({
        id: `${assessment.id}-ctrl-${control.id}`,
        title: control.title,
        description: control.description,
        source: control.gdpr_ref?.includes('AI Act') ? 'AI Act' : 'DSGVO',
        sourceArticle: control.gdpr_ref || '',
        deadline: null,
        status: 'pending',
        priority: assessment.result?.risk_level === 'HIGH' || assessment.result?.risk_level === 'UNACCEPTABLE' ? 'high' : 'medium',
        responsible: 'IT / Compliance',
        linkedSystems: assessment.title ? [assessment.title] : [],
      })
    }
  }

  return obligations
}

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

export default function ObligationsPage() {
  const { state } = useSDK()
  const [obligations, setObligations] = useState<Obligation[]>([])
  const [filter, setFilter] = useState<string>('all')
  const [loading, setLoading] = useState(true)
  const [backendAvailable, setBackendAvailable] = useState(false)
  const [backendError, setBackendError] = useState<string | null>(null)

  useEffect(() => {
    async function loadObligations() {
      try {
        const response = await fetch('/api/sdk/v1/ucca/assessments')
        if (response.ok) {
          const data = await response.json()
          const assessments = data.assessments || []
          if (assessments.length > 0) {
            const mapped = mapControlsToObligations(assessments)
            setObligations(mapped)
            setBackendAvailable(true)
            setLoading(false)
            return
          }
        }
      } catch {
        setBackendError('Backend nicht erreichbar — Pflichten aus lokalem State geladen (Offline-Modus)')
      }

      // Fallback: use obligations from SDK state
      if (state.obligations && state.obligations.length > 0) {
        setObligations(state.obligations.map(o => ({
          id: o.id,
          title: o.title,
          description: o.description || '',
          source: o.source || 'DSGVO',
          sourceArticle: o.sourceArticle || '',
          deadline: o.deadline ? new Date(o.deadline) : null,
          status: (o.status as Obligation['status']) || 'pending',
          priority: (o.priority as Obligation['priority']) || 'medium',
          responsible: o.responsible || 'Compliance Team',
          linkedSystems: o.linkedSystems || [],
        })))
      }

      setLoading(false)
    }

    loadObligations()
  }, [state.obligations])

  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>

      {/* Backend Status */}
      {backendAvailable && (
        <div className="bg-green-50 border border-green-200 rounded-lg p-3 text-sm text-green-700">
          Pflichten aus UCCA-Assessments geladen (Live-Daten)
        </div>
      )}
      {backendError && !backendAvailable && (
        <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-700 flex items-center gap-2">
          <svg className="w-4 h-4 flex-shrink-0" 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>
          {backendError}
        </div>
      )}

      {/* Loading */}
      {loading && (
        <div className="text-center py-8 text-gray-500">Lade Pflichten...</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">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) => {
            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 && !loading && (
        <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">
            Erstellen Sie zuerst ein Use Case Assessment, um automatisch Pflichten abzuleiten.
          </p>
        </div>
      )}
    </div>
  )
}
