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 RegisterScreen() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { register } = useApp();
  const router = useRouter();

  const handleRegister = async () => {
    if (!name.trim() || !email.trim() || !password.trim()) {
      Alert.alert("Datos faltantes", "Completa todos los campos.");
      return;
    }
    if (password.length < 6) {
      Alert.alert("Password corto", "Debe tener al menos 6 caracteres.");
      return;
    }

    try {
      setSubmitting(true);
      await register(name, email, password);
      // Onboarding: tras registrar, pedir que valide su domicilio.
      router.replace("/addresses");
    } catch (err) {
      Alert.alert(
        "No se pudo crear la cuenta",
        err instanceof Error ? err.message : "Error desconocido",
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        <Text style={styles.title}>Crear cuenta</Text>
        <Text style={styles.subtitle}>
          Registra tu correo para recibir alertas de recolección.
        </Text>

        <InputField placeholder="Nombre" value={name} onChangeText={setName} />
        <InputField
          placeholder="Email"
          value={email}
          onChangeText={setEmail}
        />
        <InputField
          placeholder="Password (mínimo 6 caracteres)"
          value={password}
          onChangeText={setPassword}
          secureTextEntry
        />

        <View style={{ height: 8 }} />
        <PrimaryButton
          title={submitting ? "Creando..." : "Registrarme"}
          onPress={handleRegister}
        />

        <Pressable
          onPress={() => router.replace("/login")}
          style={styles.linkWrap}
        >
          <Text style={styles.link}>
            ¿Ya tienes cuenta? <Text style={styles.linkBold}>Inicia sesión</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" },
});
