'use client'

import { useState } from 'react'
import { createModule } from '@/lib/sdk/training/api'
import { REGULATION_LABELS, FREQUENCY_LABELS } from '@/lib/sdk/training/types'

export default function ModuleCreateModal({
  onClose,
  onSaved,
}: {
  onClose: () => void
  onSaved: () => void
}) {
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    const fd = new FormData(e.currentTarget)
    try {
      await createModule({
        module_code: fd.get('module_code') as string,
        title: fd.get('title') as string,
        description: (fd.get('description') as string) || undefined,
        regulation_area: fd.get('regulation_area') as string,
        frequency_type: fd.get('frequency_type') as string,
        duration_minutes: parseInt(fd.get('duration_minutes') as string) || 30,
        pass_threshold: parseInt(fd.get('pass_threshold') as string) || 80,
      })
      onSaved()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Fehler beim Erstellen')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 max-h-[90vh] overflow-y-auto">
        <h3 className="text-lg font-semibold mb-4">Neues Schulungsmodul</h3>

        {error && (
          <div className="mb-4 text-sm text-red-600 bg-red-50 border border-red-200 rounded p-3">{error}</div>
        )}

        <form onSubmit={handleSubmit} className="space-y-3">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-gray-600 block mb-1">Modul-Code *</label>
              <input name="module_code" required className="w-full px-3 py-2 text-sm border rounded-lg" placeholder="z.B. DSGVO-001" />
            </div>
            <div>
              <label className="text-xs text-gray-600 block mb-1">Regulierungsbereich *</label>
              <select name="regulation_area" required className="w-full px-3 py-2 text-sm border rounded-lg bg-white">
                {Object.entries(REGULATION_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="text-xs text-gray-600 block mb-1">Titel *</label>
            <input name="title" required className="w-full px-3 py-2 text-sm border rounded-lg" />
          </div>
          <div>
            <label className="text-xs text-gray-600 block mb-1">Beschreibung</label>
            <textarea name="description" rows={2} className="w-full px-3 py-2 text-sm border rounded-lg" />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-gray-600 block mb-1">Frequenz</label>
              <select name="frequency_type" className="w-full px-3 py-2 text-sm border rounded-lg bg-white">
                {Object.entries(FREQUENCY_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
            <div>
              <label className="text-xs text-gray-600 block mb-1">Dauer (Minuten)</label>
              <input name="duration_minutes" type="number" defaultValue={30} min={1} className="w-full px-3 py-2 text-sm border rounded-lg" />
            </div>
          </div>
          <div>
            <label className="text-xs text-gray-600 block mb-1">Bestehensgrenze (%)</label>
            <input name="pass_threshold" type="number" defaultValue={80} min={0} max={100} className="w-full px-3 py-2 text-sm border rounded-lg" />
          </div>
          <div className="flex gap-3 pt-2">
            <button type="submit" disabled={saving} className="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
              {saving ? 'Speichere...' : 'Erstellen'}
            </button>
            <button type="button" onClick={onClose} className="px-4 py-2 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200">
              Abbrechen
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
