'use client'

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

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

type ModuleCategory = 'gdpr' | 'ai-act' | 'iso27001' | 'nis2' | 'custom'
type ModuleStatus = 'active' | 'inactive' | 'pending'

interface DisplayModule extends ServiceModule {
  category: ModuleCategory
  status: ModuleStatus
  requirementsCount: number
  controlsCount: number
  completionPercent: number
}

// =============================================================================
// AVAILABLE MODULES (Templates)
// =============================================================================

const availableModules: Omit<DisplayModule, 'status' | 'completionPercent'>[] = [
  {
    id: 'mod-gdpr',
    name: 'DSGVO Compliance',
    description: 'Datenschutz-Grundverordnung - Vollstaendige Umsetzung aller Anforderungen',
    category: 'gdpr',
    regulations: ['DSGVO', 'BDSG'],
    criticality: 'HIGH',
    processesPersonalData: true,
    hasAIComponents: false,
    requirementsCount: 45,
    controlsCount: 32,
  },
  {
    id: 'mod-ai-act',
    name: 'AI Act Compliance',
    description: 'EU AI Act - Klassifizierung und Anforderungen fuer KI-Systeme',
    category: 'ai-act',
    regulations: ['EU AI Act'],
    criticality: 'HIGH',
    processesPersonalData: false,
    hasAIComponents: true,
    requirementsCount: 28,
    controlsCount: 18,
  },
  {
    id: 'mod-iso27001',
    name: 'ISO 27001',
    description: 'Informationssicherheits-Managementsystem nach ISO/IEC 27001',
    category: 'iso27001',
    regulations: ['ISO 27001', 'ISO 27002'],
    criticality: 'MEDIUM',
    processesPersonalData: false,
    hasAIComponents: false,
    requirementsCount: 114,
    controlsCount: 93,
  },
  {
    id: 'mod-nis2',
    name: 'NIS2 Richtlinie',
    description: 'Netz- und Informationssicherheit fuer kritische Infrastrukturen',
    category: 'nis2',
    regulations: ['NIS2'],
    criticality: 'HIGH',
    processesPersonalData: false,
    hasAIComponents: false,
    requirementsCount: 36,
    controlsCount: 24,
  },
]

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

function ModuleCard({
  module,
  isActive,
  onActivate,
  onDeactivate,
}: {
  module: DisplayModule
  isActive: boolean
  onActivate: () => void
  onDeactivate: () => void
}) {
  const categoryColors = {
    gdpr: 'bg-blue-100 text-blue-700',
    'ai-act': 'bg-purple-100 text-purple-700',
    iso27001: 'bg-green-100 text-green-700',
    nis2: 'bg-orange-100 text-orange-700',
    custom: 'bg-gray-100 text-gray-700',
  }

  const statusColors = {
    active: 'bg-green-100 text-green-700',
    inactive: 'bg-gray-100 text-gray-500',
    pending: 'bg-yellow-100 text-yellow-700',
  }

  return (
    <div className={`bg-white rounded-xl border-2 p-6 transition-all ${
      isActive ? 'border-purple-400 shadow-lg' : 'border-gray-200 hover:border-purple-300'
    }`}>
      <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 ${categoryColors[module.category]}`}>
              {module.category.toUpperCase()}
            </span>
            <span className={`px-2 py-1 text-xs rounded-full ${statusColors[module.status]}`}>
              {module.status === 'active' ? 'Aktiv' : module.status === 'pending' ? 'Ausstehend' : 'Inaktiv'}
            </span>
            {module.hasAIComponents && (
              <span className="px-2 py-1 text-xs rounded-full bg-indigo-100 text-indigo-700">
                KI
              </span>
            )}
          </div>
          <h3 className="text-lg font-semibold text-gray-900">{module.name}</h3>
          <p className="text-sm text-gray-500 mt-1">{module.description}</p>
          <div className="mt-2 flex flex-wrap gap-1">
            {module.regulations.map(reg => (
              <span key={reg} className="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded">
                {reg}
              </span>
            ))}
          </div>
        </div>
      </div>

      <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
        <div>
          <span className="text-gray-500">Anforderungen:</span>
          <span className="ml-2 font-medium">{module.requirementsCount}</span>
        </div>
        <div>
          <span className="text-gray-500">Kontrollen:</span>
          <span className="ml-2 font-medium">{module.controlsCount}</span>
        </div>
      </div>

      <div className="mt-4">
        <div className="flex items-center justify-between text-sm mb-1">
          <span className="text-gray-500">Fortschritt</span>
          <span className="font-medium text-purple-600">{module.completionPercent}%</span>
        </div>
        <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full transition-all ${
              module.completionPercent === 100 ? 'bg-green-500' : 'bg-purple-600'
            }`}
            style={{ width: `${module.completionPercent}%` }}
          />
        </div>
      </div>

      <div className="mt-4 flex items-center gap-2">
        {isActive ? (
          <>
            <button className="flex-1 px-4 py-2 text-sm bg-purple-50 text-purple-700 rounded-lg hover:bg-purple-100 transition-colors">
              Konfigurieren
            </button>
            <button
              onClick={onDeactivate}
              className="px-4 py-2 text-sm text-red-600 hover:bg-red-50 rounded-lg transition-colors"
            >
              Deaktivieren
            </button>
          </>
        ) : (
          <button
            onClick={onActivate}
            className="flex-1 px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
          >
            Modul aktivieren
          </button>
        )}
      </div>
    </div>
  )
}

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

export default function ModulesPage() {
  const { state, dispatch } = useSDK()
  const [filter, setFilter] = useState<string>('all')

  // Convert SDK modules to display modules with additional UI properties
  const displayModules: DisplayModule[] = availableModules.map(template => {
    const activeModule = state.modules.find(m => m.id === template.id)
    const isActive = !!activeModule

    // Calculate completion based on linked requirements and controls
    const linkedRequirements = state.requirements.filter(r =>
      r.applicableModules.includes(template.id)
    )
    const completedRequirements = linkedRequirements.filter(
      r => r.status === 'IMPLEMENTED' || r.status === 'VERIFIED'
    )
    const completionPercent = linkedRequirements.length > 0
      ? Math.round((completedRequirements.length / linkedRequirements.length) * 100)
      : 0

    return {
      ...template,
      status: isActive ? 'active' as ModuleStatus : 'inactive' as ModuleStatus,
      completionPercent,
    }
  })

  const filteredModules = filter === 'all'
    ? displayModules
    : displayModules.filter(m => m.category === filter || m.status === filter)

  const activeModulesCount = state.modules.length
  const totalRequirements = displayModules
    .filter(m => state.modules.some(sm => sm.id === m.id))
    .reduce((sum, m) => sum + m.requirementsCount, 0)
  const totalControls = displayModules
    .filter(m => state.modules.some(sm => sm.id === m.id))
    .reduce((sum, m) => sum + m.controlsCount, 0)

  const handleActivateModule = (module: DisplayModule) => {
    const serviceModule: ServiceModule = {
      id: module.id,
      name: module.name,
      description: module.description,
      regulations: module.regulations,
      criticality: module.criticality,
      processesPersonalData: module.processesPersonalData,
      hasAIComponents: module.hasAIComponents,
    }
    dispatch({ type: 'ADD_MODULE', payload: serviceModule })
  }

  const handleDeactivateModule = (moduleId: string) => {
    // Remove module by updating state without it
    const updatedModules = state.modules.filter(m => m.id !== moduleId)
    dispatch({ type: 'SET_STATE', payload: { modules: updatedModules } })
  }

  const stepInfo = STEP_EXPLANATIONS['modules']

  return (
    <div className="space-y-6">
      {/* Step Header */}
      <StepHeader
        stepId="modules"
        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>
          Eigenes Modul 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">Verfuegbare Module</div>
          <div className="text-3xl font-bold text-gray-900">{availableModules.length}</div>
        </div>
        <div className="bg-white rounded-xl border border-green-200 p-6">
          <div className="text-sm text-green-600">Aktivierte Module</div>
          <div className="text-3xl font-bold text-green-600">{activeModulesCount}</div>
        </div>
        <div className="bg-white rounded-xl border border-blue-200 p-6">
          <div className="text-sm text-blue-600">Anforderungen (aktiv)</div>
          <div className="text-3xl font-bold text-blue-600">{totalRequirements}</div>
        </div>
        <div className="bg-white rounded-xl border border-purple-200 p-6">
          <div className="text-sm text-purple-600">Kontrollen (aktiv)</div>
          <div className="text-3xl font-bold text-purple-600">{totalControls}</div>
        </div>
      </div>

      {/* Active Modules Alert */}
      {activeModulesCount === 0 && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <svg className="w-5 h-5 text-amber-600 mt-0.5" 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>
              <h4 className="font-medium text-amber-800">Keine Module aktiviert</h4>
              <p className="text-sm text-amber-700 mt-1">
                Aktivieren Sie mindestens ein Compliance-Modul, um mit der Erfassung von Anforderungen und Kontrollen fortzufahren.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Filter */}
      <div className="flex items-center gap-2">
        <span className="text-sm text-gray-500">Filter:</span>
        {['all', 'active', 'inactive', 'gdpr', 'ai-act', 'iso27001', 'nis2'].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 === 'active' ? 'Aktiv' :
             f === 'inactive' ? 'Inaktiv' :
             f.toUpperCase()}
          </button>
        ))}
      </div>

      {/* Module Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {filteredModules.map(module => (
          <ModuleCard
            key={module.id}
            module={module}
            isActive={state.modules.some(m => m.id === module.id)}
            onActivate={() => handleActivateModule(module)}
            onDeactivate={() => handleDeactivateModule(module.id)}
          />
        ))}
      </div>

      {filteredModules.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 Module gefunden</h3>
          <p className="mt-2 text-gray-500">Passen Sie den Filter an oder fuegen Sie neue Module hinzu.</p>
        </div>
      )}
    </div>
  )
}
