'use client'

import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { useSDK } from '@/lib/sdk'
import {
  CourseCategory,
  COURSE_CATEGORY_INFO,
  CreateCourseRequest,
  GenerateCourseRequest
} from '@/lib/sdk/academy/types'
import { createCourse, generateCourse } from '@/lib/sdk/academy/api'
import { getModules } from '@/lib/sdk/training/api'
import type { TrainingModule } from '@/lib/sdk/training/types'

type CreationMode = 'manual' | 'ai'

export default function NewCoursePage() {
  const router = useRouter()
  const [mode, setMode] = useState<CreationMode>('ai')
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Manual form state
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [category, setCategory] = useState<CourseCategory>('dsgvo_basics')
  const [duration, setDuration] = useState(60)
  const [passingScore, setPassingScore] = useState(70)

  // AI generation state - module selection
  const [trainingModules, setTrainingModules] = useState<TrainingModule[]>([])
  const [selectedModuleId, setSelectedModuleId] = useState('')
  const [modulesLoading, setModulesLoading] = useState(false)

  // Load training modules on mount
  useEffect(() => {
    async function loadModules() {
      setModulesLoading(true)
      try {
        const res = await getModules()
        setTrainingModules(res.modules || [])
      } catch {
        setError('Training-Module konnten nicht geladen werden.')
      } finally {
        setModulesLoading(false)
      }
    }
    loadModules()
  }, [])

  const handleManualCreate = async () => {
    if (!title.trim()) {
      setError('Bitte geben Sie einen Kurstitel ein.')
      return
    }
    setIsLoading(true)
    setError(null)

    try {
      const tenantId = typeof window !== 'undefined'
        ? localStorage.getItem('bp_tenant_id') || 'default-tenant'
        : 'default-tenant'

      const result = await createCourse({
        tenantId,
        title: title.trim(),
        description: description.trim(),
        category,
        durationMinutes: duration,
        passingScore,
        requiredForRoles: ['all']
      } as any)

      // Navigate to the new course
      if (result && (result as any).id) {
        router.push(`/sdk/academy/${(result as any).id}`)
      } else {
        router.push('/sdk/academy')
      }
    } catch (err: any) {
      setError(err.message || 'Fehler beim Erstellen des Kurses')
    } finally {
      setIsLoading(false)
    }
  }

  const handleAIGenerate = async () => {
    if (!selectedModuleId) {
      setError('Bitte waehlen Sie ein Training-Modul aus.')
      return
    }
    setIsLoading(true)
    setError(null)

    try {
      const result = await generateCourse({
        moduleId: selectedModuleId,
      })

      if (result && result.course && result.course.id) {
        router.push(`/sdk/academy/${result.course.id}`)
      } else {
        router.push('/sdk/academy')
      }
    } catch (err: any) {
      setError(err.message || 'Fehler bei der KI-Generierung')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Link
          href="/sdk/academy"
          className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg 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="M15 19l-7-7 7-7" />
          </svg>
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Neuen Kurs erstellen</h1>
          <p className="text-sm text-gray-500 mt-1">
            Erstellen Sie einen Compliance-Schulungskurs manuell oder lassen Sie ihn von der KI generieren.
          </p>
        </div>
      </div>

      {/* Mode Toggle */}
      <div className="flex gap-2 bg-gray-100 p-1 rounded-xl w-fit">
        <button
          onClick={() => setMode('ai')}
          className={`px-6 py-2.5 rounded-lg text-sm font-medium transition-all ${
            mode === 'ai'
              ? 'bg-purple-600 text-white shadow-sm'
              : 'text-gray-600 hover:text-gray-800'
          }`}
        >
          <span className="flex items-center gap-2">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
            KI-Generierung
          </span>
        </button>
        <button
          onClick={() => setMode('manual')}
          className={`px-6 py-2.5 rounded-lg text-sm font-medium transition-all ${
            mode === 'manual'
              ? 'bg-purple-600 text-white shadow-sm'
              : 'text-gray-600 hover:text-gray-800'
          }`}
        >
          <span className="flex items-center gap-2">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
            Manuell erstellen
          </span>
        </button>
      </div>

      {/* Error Message */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-center gap-3">
          <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="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>
          <p className="text-sm text-red-700">{error}</p>
        </div>
      )}

      {/* AI Generation Form */}
      {mode === 'ai' && (
        <div className="bg-white rounded-xl border border-gray-200 p-8 space-y-6">
          <div className="flex items-start gap-3 p-4 bg-purple-50 rounded-xl">
            <svg className="w-5 h-5 text-purple-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
            <div>
              <h3 className="font-medium text-purple-800">Kurs aus Training-Modul generieren</h3>
              <p className="text-sm text-purple-600 mt-1">
                Waehlen Sie ein bestehendes Training-Modul aus. Der Academy-Kurs wird automatisch mit den generierten Inhalten und Quizfragen erstellt.
              </p>
            </div>
          </div>

          {/* Module Selection */}
          {modulesLoading ? (
            <div className="flex items-center gap-3 py-8 justify-center text-gray-500">
              <svg className="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
              Training-Module werden geladen...
            </div>
          ) : trainingModules.length === 0 ? (
            <div className="text-center py-8">
              <p className="text-gray-500">Keine Training-Module gefunden.</p>
              <p className="text-sm text-gray-400 mt-1">Bitte erstellen Sie zuerst Module unter Schulung &gt; Module.</p>
            </div>
          ) : (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Training-Modul auswaehlen *</label>
              <p className="text-xs text-gray-400 mb-3">Module mit bestehendem Kurs werden beim Generieren uebersprungen oder neu verknuepft.</p>
              <div className="grid gap-3 max-h-[400px] overflow-y-auto pr-2">
                {trainingModules.map((mod) => (
                  <button
                    key={mod.id}
                    type="button"
                    onClick={() => setSelectedModuleId(mod.id)}
                    className={`p-4 rounded-xl border-2 text-left transition-all ${
                      selectedModuleId === mod.id
                        ? 'border-purple-500 bg-purple-50'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className={`text-sm font-medium ${selectedModuleId === mod.id ? 'text-purple-700' : 'text-gray-700'}`}>
                        {mod.title}
                      </div>
                      <div className="flex items-center gap-2">
                        {mod.academy_course_id && (
                          <span className="text-xs px-2 py-0.5 rounded-full bg-green-100 text-green-700">Kurs vorhanden</span>
                        )}
                        <span className="text-xs px-2 py-1 rounded-full bg-gray-100 text-gray-600">
                          {mod.regulation_area}
                        </span>
                      </div>
                    </div>
                    {mod.description && (
                      <div className="text-xs text-gray-500 mt-1 line-clamp-2">{mod.description}</div>
                    )}
                    <div className="flex gap-3 mt-2 text-xs text-gray-400">
                      <span>{mod.duration_minutes} Min.</span>
                      <span>{mod.frequency_type}</span>
                      <span>{mod.module_code}</span>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Submit */}
          <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
            <Link
              href="/sdk/academy"
              className="px-6 py-2.5 text-gray-700 hover:bg-gray-100 rounded-xl transition-colors"
            >
              Abbrechen
            </Link>
            <button
              onClick={handleAIGenerate}
              disabled={isLoading || !selectedModuleId}
              className="px-6 py-2.5 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {isLoading ? (
                <>
                  <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  Kurs wird generiert...
                </>
              ) : (
                <>
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                  </svg>
                  Kurs generieren
                </>
              )}
            </button>
          </div>
        </div>
      )}

      {/* Manual Creation Form */}
      {mode === 'manual' && (
        <div className="bg-white rounded-xl border border-gray-200 p-8 space-y-6">
          {/* Title */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Kurstitel *</label>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="z.B. DSGVO-Grundlagen fuer Mitarbeiter"
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-base"
            />
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Beschreibung</label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Kurze Beschreibung des Kursinhalts..."
              rows={3}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 resize-none"
            />
          </div>

          {/* Category */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Kategorie *</label>
            <select
              value={category}
              onChange={(e) => setCategory(e.target.value as CourseCategory)}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            >
              {Object.entries(COURSE_CATEGORY_INFO).map(([cat, info]) => (
                <option key={cat} value={cat}>{info.label}</option>
              ))}
            </select>
          </div>

          {/* Duration & Passing Score */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Dauer (Minuten)</label>
              <input
                type="number"
                value={duration}
                onChange={(e) => setDuration(parseInt(e.target.value) || 60)}
                min={15}
                max={480}
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Bestehensgrenze (%)</label>
              <input
                type="number"
                value={passingScore}
                onChange={(e) => setPassingScore(parseInt(e.target.value) || 70)}
                min={0}
                max={100}
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
              />
            </div>
          </div>

          {/* Submit */}
          <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
            <Link
              href="/sdk/academy"
              className="px-6 py-2.5 text-gray-700 hover:bg-gray-100 rounded-xl transition-colors"
            >
              Abbrechen
            </Link>
            <button
              onClick={handleManualCreate}
              disabled={isLoading || !title.trim()}
              className="px-6 py-2.5 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {isLoading ? (
                <>
                  <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  Wird erstellt...
                </>
              ) : (
                'Kurs erstellen'
              )}
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
