import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router";
import { useState } from "react";
import {
    ActivityIndicator,
    Platform,
    Pressable,
    Text,
    TextInput,
    View,
} from "react-native";
import Logo from "./src/components/ui/webLogo";
import { styles } from "./src/styles/login";
import { colors } from "./src/theme/colors";
import { gradients } from "./src/theme/gradients";

export default function Login() {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [showPassword, setShowPassword] = useState(false);
    const [error, setError] = useState("");
    const [loading, setLoading] = useState(false);
    const [emailFocused, setEmailFocused] = useState(false);
    const [passwordFocused, setPasswordFocused] = useState(false);

    const { login } = useAuth();
    const router = useRouter();
    const logoSize = Platform.OS === "web" ? 400 : 400;

    const handleLogin = async () => {
        setError("");

        // Validación
        if (!email || !password) {
            setError("Por favor, completa todos los campos");
            return;
        }

        if (!email.includes("@")) {
            setError("Por favor, introduce un email válido");
            return;
        }

        if (password.length < 6) {
            setError("La contraseña debe tener al menos 6 caracteres");
            return;
        }

        setLoading(true);

        try {
            await login(email, password);
            router.replace("/");
        } catch (err: any) {
            // Mensajes de error en español
            if (err.code === "auth/invalid-credential") {
                setError("Email o contraseña incorrectos");
            } else if (err.code === "auth/user-not-found") {
                setError("No existe una cuenta con este email");
            } else if (err.code === "auth/wrong-password") {
                setError("Contraseña incorrecta");
            } else if (err.code === "auth/too-many-requests") {
                setError("Demasiados intentos. Intenta de nuevo más tarde");
            } else if (err.code === "auth/network-request-failed") {
                setError("Error de conexión. Verifica tu internet");
            } else {
                setError("Error al iniciar sesión. Intenta de nuevo");
            }
        } finally {
            setLoading(false);
        }
    };

    return (
        <LinearGradient colors={gradients.background_white} style={styles.container}>
            <View style={styles.logoContainer}>
                <Logo size={logoSize} />
                <Text style={styles.subtitle}>Sistema de gestión profesional</Text>
            </View>

            <View style={styles.formContainer}>
                {/* Email Input */}
                <View style={styles.inputWrapper}>
                    <Text style={styles.label}>Email</Text>
                    <View
                        style={[
                            styles.inputContainer,
                            emailFocused && styles.inputContainerFocused,
                        ]}
                    >
                        <TextInput
                            style={styles.input}
                            placeholder="tu@email.com"
                            value={email}
                            onChangeText={setEmail}
                            keyboardType="email-address"
                            autoCapitalize="none"
                            autoComplete="email"
                            onFocus={() => setEmailFocused(true)}
                            onBlur={() => setEmailFocused(false)}
                            editable={!loading}
                        />
                    </View>
                </View>

                {/* Password Input */}
                <View style={styles.inputWrapper}>
                    <Text style={styles.label}>Contraseña</Text>
                    <View
                        style={[
                            styles.inputContainer,
                            passwordFocused && styles.inputContainerFocused,
                        ]}
                    >
                        <TextInput
                            style={styles.input}
                            placeholder="••••••••"
                            value={password}
                            onChangeText={setPassword}
                            secureTextEntry={!showPassword}
                            autoCapitalize="none"
                            autoComplete="password"
                            onFocus={() => setPasswordFocused(true)}
                            onBlur={() => setPasswordFocused(false)}
                            editable={!loading}
                        />
                        <Pressable
                            onPress={() => setShowPassword(!showPassword)}
                            style={styles.eyeButton}
                            disabled={loading}
                        >
                            <Ionicons
                                name={showPassword ? "eye-off" : "eye"}
                                size={24}
                                color={colors.gray500}
                            />
                        </Pressable>
                    </View>
                </View>

                {/* Error Message */}
                {error ? <Text style={styles.errorText}>{error}</Text> : null}

                {/* Login Button */}
                <Pressable
                    onPress={handleLogin}
                    disabled={loading}
                    style={({ pressed }) => [
                        styles.buttonWrapper,
                        loading && styles.buttonDisabled,
                        pressed && { transform: [{ scale: 0.97 }] },
                    ]}
                >
                    <LinearGradient colors={gradients.button} style={styles.button}>
                        {loading ? (
                            <ActivityIndicator color={colors.white} size="small" />
                        ) : (
                            <Text style={styles.buttonText}>Iniciar Sesión</Text>
                        )}
                    </LinearGradient>
                </Pressable>
            </View>
        </LinearGradient>
    );
}
