'use client'

import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { StepHeader, STEP_EXPLANATIONS } from '@/components/sdk/StepHeader'
import { ModuleCard } from './_components/ModuleCard'
import { useModules } from './_hooks/useModules'
import type { ModuleCategory } from './_hooks/useModules'

export default function ModulesPage() {
  const router = useRouter()
  const [filter, setFilter] = useState<string>('all')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [newModuleName, setNewModuleName] = useState('')
  const [newModuleCategory, setNewModuleCategory] = useState<ModuleCategory>('custom')
  const [newModuleDescription, setNewModuleDescription] = useState('')

  const {
    state,
    availableModules,
    displayModules,
    isLoadingModules,
    backendError,
    actionError,
    activeModulesCount,
    totalRequirements,
    totalControls,
    handleActivateModule,
    handleDeactivateModule,
    handleCreateModule,
  } = useModules()

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

  async function onCreateModule() {
    const ok = await handleCreateModule(newModuleName, newModuleCategory, newModuleDescription)
    if (ok) {
      setShowCreateModal(false)
      setNewModuleName('')
      setNewModuleCategory('custom')
      setNewModuleDescription('')
    }
  }

  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
          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>
          Eigenes Modul erstellen
        </button>
      </StepHeader>

      {/* Error Toast */}
      {actionError && (
        <div className="fixed top-4 right-4 z-50 bg-red-50 border border-red-200 rounded-lg p-4 shadow-lg max-w-sm">
          <div className="flex items-start gap-2">
            <svg className="w-5 h-5 text-red-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
            <p className="text-sm text-red-700">{actionError}</p>
          </div>
        </div>
      )}

      {/* Create Module Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white rounded-xl p-6 w-full max-w-md shadow-2xl">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">Eigenes Modul erstellen</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
                <input
                  type="text"
                  value={newModuleName}
                  onChange={e => setNewModuleName(e.target.value)}
                  placeholder="z.B. ISO 42001 AI Management"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Kategorie</label>
                <select
                  value={newModuleCategory}
                  onChange={e => setNewModuleCategory(e.target.value as ModuleCategory)}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
                >
                  <option value="gdpr">DSGVO</option>
                  <option value="ai-act">AI Act</option>
                  <option value="iso27001">ISO 27001</option>
                  <option value="nis2">NIS2</option>
                  <option value="custom">Eigene</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
                <textarea
                  value={newModuleDescription}
                  onChange={e => setNewModuleDescription(e.target.value)}
                  placeholder="Was deckt dieses Modul ab?"
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
                />
              </div>
            </div>
            <div className="flex justify-end gap-2 mt-6">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg"
              >
                Abbrechen
              </button>
              <button
                onClick={onCreateModule}
                disabled={!newModuleName.trim()}
                className="px-4 py-2 text-sm bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50"
              >
                Erstellen
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Backend Status */}
      {backendError && (
        <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-700">
          {backendError}
        </div>
      )}

      {/* Loading */}
      {isLoadingModules && (
        <div className="text-center py-8 text-gray-500">Lade Module vom Backend...</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">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)}
            onConfigure={() => router.push(`/sdk/modules/${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>
  )
}
