import React, { useState } from "react";

import {
  Alert,
  Image,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  View,
} from "react-native";

import { Button } from "@/components/Button";
import { Input } from "@/components/Input";
import { useAuth } from "@/contexts/AuthContext";
import { api, setAuthToken } from "@/server/api";
import { salvarUsuario } from "@/services/db";
import { getUserIdFromToken } from "@/utils/jwt";
import { Link } from "expo-router";

function isValidEmail(emailToCheck: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailToCheck);
}

export default function Signup() {
  const { signup } = useAuth();
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSignUp() {
    const nameTrimmed = name.trim();
    const emailTrimmed = email.trim();

    if (!nameTrimmed || !emailTrimmed || !password.trim() || !confirmPassword.trim()) {
      Alert.alert("Cadastrar", "Por favor, preencha todos os campos.");
      return;
    }

    if (!isValidEmail(emailTrimmed)) {
      Alert.alert("Email inválido", "Por favor, digite um email válido (ex: usuario@email.com).");
      return;
    }

    if (password.length < 6) {
      Alert.alert("Senha fraca", "A senha deve ter pelo menos 6 caracteres.");
      return;
    }

    if (password !== confirmPassword) {
      Alert.alert("Cadastrar", "As senhas não coincidem.");
      return;
    }

    try {
      setLoading(true);
      const { data } = await api.post("/auth/register", {
        name: nameTrimmed,
        email: emailTrimmed,
        password,
      });

      setAuthToken(data.accessToken);

      const userId = getUserIdFromToken(data.accessToken) ?? data.id;

      await salvarUsuario({
        id: userId,
        email: emailTrimmed,
        name: nameTrimmed,
        token: data.accessToken,
      });

      await signup(nameTrimmed, emailTrimmed, userId, data.accessToken);
    } catch (err: any) {
      const message = err.response?.data?.error ?? err.message ?? "Erro ao criar conta.";
      Alert.alert("Erro", message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior={Platform.OS === "ios" ? "padding" : "height"}
    >
      <ScrollView
        contentContainerStyle={{ flexGrow: 1 }}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.container}>
          <Image
            source={require("@/assets/toptran.png")}
            style={styles.illustration}
          />

          <Text style={styles.title}>Cadastrar</Text>
          <Text style={styles.subtitle}>Crie sua conta para acessar.</Text>

          <View style={styles.form}>
            <Input placeholder="Nome" onChangeText={setName} />
            <Input
              placeholder="E-mail"
              keyboardType="email-address"
              autoCapitalize="none"
              onChangeText={setEmail}
            />
            <Input
              placeholder="Senha"
              secureTextEntry
              onChangeText={setPassword}
            />
            <Input
              placeholder="Confirmar Senha"
              secureTextEntry
              onChangeText={setConfirmPassword}
            />
            <Button
              label={loading ? "Cadastrando..." : "Cadastrar"}
              onPress={handleSignUp}
              disabled={loading}
            />
          </View>

          <Text style={styles.footerText}>
            Já tem uma conta?{" "}
            <Link href={"/"} style={styles.footerLink}>
              Entre aqui.
            </Link>
          </Text>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#0e0d0d",
    padding: 32,
  },
  illustration: {
    width: "100%",
    height: 330,
    resizeMode: "contain",
    marginTop: 62,
  },
  title: {
    marginTop: 62,
    fontSize: 32,
    fontWeight: "900",
    color: "#e7e7e7",
  },
  subtitle: {
    fontSize: 16,
    color: "#a1a1a1",
  },
  form: {
    marginTop: 24,
    gap: 16,
  },
  footerText: {
    textAlign: "center",
    marginTop: 24,
    color: "#a1a1a1",
  },
  footerLink: {
    color: "#007AFF",
    fontWeight: "700",
  },
});
