import { Link } from 'expo-router';
import { useState } from 'react';
import { KeyboardAvoidingView, Platform, Pressable, ScrollView, Text, View } from 'react-native';
import { Button, TextInput } from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useAuth } from '@/context/AuthContext';
import { useUiStore } from '@/stores/ui-store';

export default function LoginScreen() {
  const { signIn } = useAuth();
  const lastEmail = useUiStore((s) => s.lastAuthEmail);
  const [email, setEmail] = useState(lastEmail);
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  return (
    <SafeAreaView className="flex-1 bg-slate-50">
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        className="flex-1"
      >
        <ScrollView
          keyboardShouldPersistTaps="handled"
          contentContainerClassName="flex-grow justify-center px-6 py-10"
        >
          <View className="mb-10">
            <Text className="text-3xl font-bold text-slate-900">Connexion</Text>
            <Text className="mt-2 text-base text-slate-600">
              Espace marchand de biens — accès sécurisé
            </Text>
          </View>

          {error ? (
            <Text className="mb-4 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
              {error}
            </Text>
          ) : null}

          <TextInput
            label="E-mail"
            mode="outlined"
            value={email}
            onChangeText={setEmail}
            autoCapitalize="none"
            keyboardType="email-address"
            autoComplete="email"
            className="mb-3 bg-white"
            style={{ backgroundColor: '#fff' }}
          />
          <TextInput
            label="Mot de passe"
            mode="outlined"
            value={password}
            onChangeText={setPassword}
            secureTextEntry
            autoComplete="password"
            className="mb-6 bg-white"
            style={{ backgroundColor: '#fff' }}
          />

          <Button
            mode="contained"
            onPress={async () => {
              setError(null);
              setLoading(true);
              const r = await signIn(email.trim(), password);
              setLoading(false);
              if (r.error) {
                setError(r.error);
                return;
              }
              useUiStore.getState().setLastAuthEmail(email.trim());
            }}
            loading={loading}
            disabled={loading}
            buttonColor="#1D4ED8"
            textColor="#ffffff"
            style={{ borderRadius: 10, paddingVertical: 4 }}
          >
            Se connecter
          </Button>

          <View className="mt-8 items-center">
            <Text className="text-slate-600">Pas encore de compte ?</Text>
            <Link href="/auth/register" asChild>
              <Pressable className="mt-2 py-2">
                <Text className="font-semibold text-primary">Créer un compte</Text>
              </Pressable>
            </Link>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
