import { useRouter } from 'expo-router';
import { useState } from 'react';
import { KeyboardAvoidingView, Platform, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

import { Button, ErrorNote, Field } from '@/components/ui';
import { fehlertext, registrieren } from '@/lib/auth';
import { useSession } from '@/lib/session';
import { colors, space, text } from '@/theme/tokens';

export default function RegistrierenScreen() {
  const router = useRouter();
  const { neuLaden } = useSession();
  const [label, setLabel] = useState('');
  const [email, setEmail] = useState('');
  const [passwort, setPasswort] = useState('');
  const [fehler, setFehler] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const bereit = label.trim().length > 1 && email.includes('@') && passwort.length >= 8;

  async function absenden() {
    setFehler(null);
    setBusy(true);
    try {
      await registrieren(email.trim(), passwort, label.trim());
      await neuLaden(); // Session-Zustand aktualisieren – der Gate leitet dann selbst weiter
    } catch (e) {
      setFehler(fehlertext(e));
      setBusy(false);
    }
  }

  return (
    <SafeAreaView style={s.safe}>
      <KeyboardAvoidingView
        style={s.flex}
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
        <ScrollView contentContainerStyle={s.body} keyboardShouldPersistTaps="handled">
          <Text style={s.titel}>Konto erstellen</Text>
          <Text style={s.unter}>Ein Konto ist eine Marke. Der Name lässt sich später ändern.</Text>

          {fehler ? <ErrorNote message={fehler} /> : null}

          <Field
            label="Name der Marke"
            value={label}
            onChangeText={setLabel}
            autoCapitalize="words"
            placeholder="z. B. Modaily"
          />
          <Field
            label="E-Mail"
            value={email}
            onChangeText={setEmail}
            autoCapitalize="none"
            autoComplete="email"
            keyboardType="email-address"
            placeholder="du@marke.de"
          />
          <Field
            label="Passwort"
            value={passwort}
            onChangeText={setPasswort}
            secureTextEntry
            autoComplete="new-password"
            placeholder="mindestens 8 Zeichen"
          />

          <View style={s.actions}>
            <Button title="Konto erstellen" onPress={absenden} busy={busy} disabled={!bereit} />
            <Button title="Zurück" variant="ghost" onPress={() => router.back()} />
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const s = StyleSheet.create({
  safe: { flex: 1, backgroundColor: colors.bg },
  flex: { flex: 1 },
  body: { padding: space.xl, gap: space.lg },
  titel: { ...text.title, color: colors.txt },
  unter: { ...text.body, color: colors.mut, marginTop: -space.sm },
  actions: { gap: space.md, marginTop: space.md },
});
