import { useState } from 'react'
import { registerUser, login, getMe } from '../../api/directus'
import { useAuth } from '../../context/AuthContext'
import { FormGroup, Input, Button, Alert, StepDots } from './ui'

export default function RegisterStep1({ onSuccess }) {
  const { saveToken } = useAuth()
  const [email, setEmail] = useState('')
  const [pw, setPw] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e) => {
    e?.preventDefault()
    if (!email || !pw) { setError('Bitte alle Felder ausfüllen.'); return }
    if (pw.length < 8) { setError('Passwort muss mindestens 8 Zeichen haben.'); return }
    setError(''); setLoading(true)
    try {
      await registerUser(email, pw)
      const { access_token } = await login(email, pw)
      saveToken(access_token)
      const me = await getMe(access_token)
      onSuccess(me.id, access_token)
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <StepDots current={0} total={2} />
      <Alert message={error} />
      <FormGroup label="E-Mail">
        <Input type="email" placeholder="deine@email.de" value={email}
          onChange={e => setEmail(e.target.value)} autoComplete="email" autoFocus />
      </FormGroup>
      <FormGroup label="Passwort">
        <Input type="password" placeholder="Mindestens 8 Zeichen" value={pw}
          onChange={e => setPw(e.target.value)} autoComplete="new-password" />
      </FormGroup>
      <Button type="submit" loading={loading} disabled={loading}>
        {loading ? 'Weiter…' : 'Weiter'}
      </Button>
    </form>
  )
}
