import { useState } from "react";
import { View, Text, StyleSheet, Alert, Pressable } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";

import { COLORS } from "../constants/colors";
import InputField from "../components/InputField";
import PrimaryButton from "../components/PrimaryButton";

import { useApp } from "../context/AppContext";

export default function LoginScreen() {
  const [email, setEmail] = useState("ana@test.com");
  const [password, setPassword] = useState("123456");
  const [submitting, setSubmitting] = useState(false);
  const { login } = useApp();
  const router = useRouter();

  const handleLogin = async () => {
    try {
      setSubmitting(true);
      await login(email, password);
      router.replace("/");
    } catch (err) {
      Alert.alert("Error", err instanceof Error ? err.message : "Login failed");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        <Text style={styles.title}>Iniciar sesión</Text>
        <Text style={styles.subtitle}>
          Accede para ver el estado del camión en tu zona.
        </Text>

        <InputField
          placeholder="Email"
          value={email}
          onChangeText={setEmail}
        />
        <InputField
          placeholder="Password"
          value={password}
          onChangeText={setPassword}
          secureTextEntry
        />

        <View style={{ height: 8 }} />
        <PrimaryButton
          title={submitting ? "Cargando..." : "Entrar"}
          onPress={handleLogin}
        />

        <Pressable
          onPress={() => router.replace("/register")}
          style={styles.linkWrap}
        >
          <Text style={styles.link}>
            ¿No tienes cuenta?{" "}
            <Text style={styles.linkBold}>Regístrate</Text>
          </Text>
        </Pressable>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: COLORS.background },
  content: { flex: 1, padding: 24, justifyContent: "center" },
  title: {
    fontSize: 26,
    fontWeight: "bold",
    textAlign: "center",
    marginBottom: 6,
  },
  subtitle: {
    fontSize: 14,
    color: "#6B7280",
    textAlign: "center",
    marginBottom: 22,
  },
  linkWrap: { marginTop: 18, alignItems: "center" },
  link: { fontSize: 14, color: "#6B7280" },
  linkBold: { color: "#0E8A61", fontWeight: "700" },
});
