'use client'

import { useState } from 'react'
import { useTheme } from '@/lib/ThemeContext'
import { BUNDESLAENDER } from '@/app/schulkalender/types'

interface BundeslandWizardProps {
  onSave: (bundesland: string) => Promise<void>
}

export function BundeslandWizard({ onSave }: BundeslandWizardProps) {
  const { isDark } = useTheme()
  const [selected, setSelected] = useState('DE-NI')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleSave = async () => {
    setSaving(true)
    setError(null)
    try {
      await onSave(selected)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Speichern fehlgeschlagen')
    } finally {
      setSaving(false)
    }
  }

  const cardClass = isDark ? 'bg-white/10 border-white/20 text-white' : 'bg-white/80 border-black/10 text-slate-900'
  const selectClass = isDark ? 'bg-white/10 border-white/20 text-white' : 'bg-white border-slate-300 text-slate-900'

  return (
    <div className={`max-w-xl mx-auto rounded-2xl border backdrop-blur-xl p-6 ${cardClass}`} data-testid="bundesland-wizard">
      <h2 className="text-xl font-semibold mb-2">Willkommen im Schulkalender</h2>
      <p className={`text-sm mb-4 ${isDark ? 'text-white/70' : 'text-slate-600'}`}>
        Waehle das Bundesland deiner Schule. Damit laden wir Ferien und
        Feiertage aus dem offiziellen Datensatz fuer die naechsten drei
        Schuljahre.
      </p>
      <div className="mb-4">
        <label className="block text-sm mb-1 opacity-70">Bundesland</label>
        <select
          value={selected}
          onChange={e => setSelected(e.target.value)}
          data-testid="bundesland-select"
          className={`w-full px-3 py-2 rounded-lg border ${selectClass}`}
        >
          {BUNDESLAENDER.map(b => (
            <option key={b.code} value={b.code}>{b.name}</option>
          ))}
        </select>
      </div>
      {error && (
        <div className="mb-3 p-2 rounded-lg bg-red-500/20 border border-red-500/40 text-red-300 text-sm">
          {error}
        </div>
      )}
      <button
        onClick={handleSave}
        disabled={saving}
        data-testid="bundesland-save"
        className="w-full px-4 py-2 rounded-lg bg-indigo-500 hover:bg-indigo-600 text-white font-medium disabled:opacity-50"
      >
        {saving ? 'Speichert…' : 'Bundesland uebernehmen'}
      </button>
    </div>
  )
}
