import { useState, useEffect } from 'react'
import { checkUsername, createProfile, getLanguageOptions } from '../../api/directus'
import { useAuth } from '../../context/AuthContext'
import { FormGroup, Input, Select, Button, Alert, StepDots } from './ui'

export default function RegisterStep2({ userId, userToken, onSuccess }) {
  const { setUser } = useAuth()
  const [username, setUsername]     = useState('')
  const [nativeLang, setNativeLang] = useState('')
  const [targetLang, setTargetLang] = useState('')
  const [languages, setLanguages]   = useState([])
  const [error, setError]           = useState('')
  const [loading, setLoading]       = useState(false)

  useEffect(() => {
    getLanguageOptions()
      .then(setLanguages)
      .catch(() => setError('Sprachen konnten nicht geladen werden.'))
  }, [])

  const handleSubmit = async (e) => {
    e?.preventDefault()
    if (!username || !nativeLang || !targetLang) {
      setError('Bitte alle Felder ausfüllen.'); return
    }
    if (nativeLang === targetLang) {
      setError('Muttersprache und Zielsprache dürfen nicht gleich sein.'); return
    }
    if (!/^[a-zA-Z0-9_]{3,20}$/.test(username)) {
      setError('Username: 3–20 Zeichen, nur Buchstaben, Zahlen und _'); return
    }
    setError(''); setLoading(true)
    try {
      const available = await checkUsername(username, userToken)
      if (!available) {
        setError('Dieser Username ist bereits vergeben.'); setLoading(false); return
      }
      await createProfile({ userId, username, nativeLang, targetLang, userToken })
      setUser({ id: userId, username: userId, language_native: nativeLang, language_target: targetLang })
      onSuccess(username)
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <StepDots current={1} total={2} />
      <Alert message={error} />
      <FormGroup label="Username">
        <Input
          type="text"
          placeholder="z. B. tim_lernt"
          value={username}
          onChange={e => setUsername(e.target.value)}
          autoFocus
          autoComplete="username"
        />
      </FormGroup>
      <FormGroup label="Deine Muttersprache">
        <Select value={nativeLang} onChange={e => setNativeLang(e.target.value)}>
          <option value="">Bitte wählen…</option>
          {languages.map(l => (
            <option key={l.id} value={l.id}>{l.flag} {l.label}</option>
          ))}
        </Select>
      </FormGroup>
      <FormGroup label="Ich lerne…">
        <Select value={targetLang} onChange={e => setTargetLang(e.target.value)}>
          <option value="">Bitte wählen…</option>
          {languages
            .filter(l => l.id !== nativeLang)
            .map(l => (
              <option key={l.id} value={l.id}>{l.flag} {l.label}</option>
            ))}
        </Select>
      </FormGroup>
      <Button type="submit" loading={loading} disabled={loading || languages.length === 0}>
        {loading ? 'Erstelle Profil…' : 'Loslegen'}
      </Button>
    </form>
  )
}
