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

export default function LoginForm({ onNeedsProfile }) {
  const { saveToken, setUser } = 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 E-Mail und Passwort eingeben.'); return }
    setError(''); setLoading(true)
    try {
      const { access_token } = await login(email, pw)
      saveToken(access_token)
      const me = await getMe(access_token)
      setUser(me)
      if (!me.username || !me.language_native || !me.language_target) {
        onNeedsProfile(me.id, access_token)
      }
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <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="••••••••" value={pw}
          onChange={e => setPw(e.target.value)} autoComplete="current-password" />
      </FormGroup>
      <Button type="submit" loading={loading} disabled={loading}>
        {loading ? 'Anmelden…' : 'Anmelden'}
      </Button>
    </form>
  )
}
