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 { anmelden, fehlertext } from '@/lib/auth';
import { useSession } from '@/lib/session';
import { colors, space, text } from '@/theme/tokens';

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

  async function absenden() {
    setFehler(null);
    setBusy(true);
    try {
      await anmelden(email.trim(), passwort);
      await neuLaden();
    } 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}>Anmelden</Text>

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

          <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="current-password"
          />

          <View style={s.actions}>
            <Button
              title="Anmelden"
              onPress={absenden}
              busy={busy}
              disabled={!email.includes('@') || passwort.length < 8}
            />
            <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 },
  actions: { gap: space.md, marginTop: space.md },
});
