import { router } from 'expo-router';
import { useState } from 'react';
import {
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { LabeledField } from '../../src/components/LabeledField';
import { PrimaryButton } from '../../src/components/PrimaryButton';
import { useApp } from '../../src/context/AppContext';
import { colors } from '../../src/theme/colors';

export default function LoginScreen() {
  const insets = useSafeAreaInsets();
  const app = useApp();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  if (app.runtimeMode !== 'cloud' || !app.supabase) {
    return (
      <View style={[styles.box, { paddingTop: insets.top }]}>
        <Text style={styles.err}>
          Configurez d’abord Supabase dans Réglages, puis revenez ici.
        </Text>
        <PrimaryButton
          title="Ouvrir Réglages"
          onPress={() => router.replace('/(tabs)/reglages')}
        />
      </View>
    );
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1, backgroundColor: colors.bg }}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <ScrollView
        keyboardShouldPersistTaps="handled"
        contentContainerStyle={{
          padding: 20,
          paddingTop: insets.top + 12,
          paddingBottom: insets.bottom + 24,
        }}
      >
        <LabeledField
          label="E-mail"
          autoCapitalize="none"
          keyboardType="email-address"
          value={email}
          onChangeText={setEmail}
        />
        <LabeledField
          label="Mot de passe"
          secureTextEntry
          value={password}
          onChangeText={setPassword}
        />
        {err ? <Text style={styles.err}>{err}</Text> : null}
        <PrimaryButton
          title="Connexion"
          loading={loading}
          onPress={async () => {
            setErr(null);
            setLoading(true);
            const r = await app.signIn(email.trim(), password);
            setLoading(false);
            if (r.error) {
              setErr(r.error);
              return;
            }
            router.replace('/(tabs)');
          }}
        />
        <PrimaryButton
          title="Créer un compte"
          variant="ghost"
          onPress={() => router.push('/auth/register')}
          containerStyle={{ marginTop: 12 }}
        />
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  box: { flex: 1, padding: 20, backgroundColor: colors.bg, gap: 12 },
  err: { color: colors.danger, marginBottom: 12 },
});
