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 { COLORS, SPACING } from "@/constants/theme";
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";

export default function IndexPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const { login } = useAuth();

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

  async function handleSignIn() {
    const emailTrimmed = email.trim();
    const passwordTrimmed = password.trim();

    if (!emailTrimmed || !passwordTrimmed) {
      Alert.alert("Entrar", "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 (passwordTrimmed.length < 6) {
      Alert.alert("Senha fraca", "A senha deve ter pelo menos 6 caracteres.");
      return;
    }

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

      setAuthToken(data.accessToken);

      const userName = data.name || emailTrimmed.split("@")[0];

      const userId = await salvarUsuario({
        id: getUserIdFromToken(data.accessToken) ?? data.id,
        email: emailTrimmed,
        name: userName,
        token: data.accessToken,
      });

      await login(emailTrimmed, passwordTrimmed, data.accessToken, {
        id: userId,
        email: emailTrimmed,
        name: userName,
      });
    } catch (err: any) {
      const message = err.response?.data?.error ?? err.message ?? "Erro ao fazer login.";
      Alert.alert("Erro", message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior={Platform.select({ ios: "padding", android: "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}>Entrar</Text>
          <Text style={styles.subtitle}>
            Acesse sua conta com e-mail e senha.
          </Text>

          <View style={styles.form}>
            <Input
              placeholder="E-mail"
              keyboardType="email-address"
              autoCapitalize="none"
              onChangeText={setEmail}
            />

            <Input
              placeholder="Senha"
              secureTextEntry
              onChangeText={setPassword}
            />

            <Button
              label={loading ? "Entrando..." : "Entrar"}
              onPress={handleSignIn}
              disabled={loading}
            />
          </View>

          <Text style={styles.footerText}>
            Não tem uma conta?{" "}
            <Link href={"/signup"} style={styles.footerLink}>
              Cadastre-se aqui.
            </Link>
          </Text>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
    padding: SPACING.xxl,
  },
  illustration: {
    width: "100%",
    height: 330,
    resizeMode: "contain",
    marginTop: SPACING.xxl,
  },
  title: {
    marginTop: SPACING.xxl,
    fontSize: 32,
    fontWeight: "900",
    color: COLORS.text,
  },
  subtitle: {
    fontSize: 16,
    color: COLORS.textSecondary,
  },
  form: {
    marginTop: SPACING.lg,
    gap: SPACING.lg,
  },
  footerText: {
    textAlign: "center",
    marginTop: SPACING.lg,
    color: COLORS.textSecondary,
  },
  footerLink: {
    color: "#007AFF",
    fontWeight: "700",
  },
});
