import { useAlert } from '@/components/AlertComponent';
import api from '@/utils/api';
import { AuthContext } from '@/utils/authContext';
import { Eye, EyeOff, Lock, LogIn, User } from 'lucide-react-native';
import { StatusBar } from 'expo-status-bar';
import React, { useContext, useState } from 'react';
import { Image, Platform, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';

export default function LoginScreen() {
    const alert = useAlert();
    const authContext = useContext(AuthContext);
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [isLoading, setIsLoading] = useState(false);

    // Login Handler function
    const handleLogin = async () => {
        if (!username || !password) {
            alert.showAlert('error', 'Attenzione', 'Inserisci username e password');
            return;
        }
        setIsLoading(true);

        try {
            username.trim();
            password.trim();

            // Execute login request
            const response = await api.post("/user/login", {
                username: username,
                password: password
            });

            if (response.data && response.data.success === false) {
                alert.showAlert('error', 'Login Fallito', 'Credenziali non valide.');
                setIsLoading(false);
                return;
            }

            const token = response.data.auth_key;
            const user = {
                firstName: response.data.nome,
                lastName: response.data.cognome,
                email: response.data.email,
                isAdmin: response.data.isAdmin
            };

            console.log("Login riuscito. Token:", token);
            console.log("Dati utente:", user);

            // Pass token and user data to the context which will handle saving and redirect
            authContext.logIn(token, user);
        } catch (error: any) {
            let message = "Si è verificato un errore durante l'accesso.";

            if (error.response) {
                if (error.response.status === 401) {
                    message = "Credenziali non valide."
                } else {
                    console.error("Login Error:", error);
                    message = `Errore Server: ${error.response.data.message || error.response.status}`;
                }
            } else if (error.request) {
                // Server not reachable
                console.error("Login Error:", error);
                message = "Impossibile contattare il server. Controlla la connessione.";
            } else {
                console.error("Login Error:", error);
            }

            alert.showAlert('error', "Login Fallito", message);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <View className="flex-1 bg-primary-dark h-screen overflow-hidden">
            <StatusBar style="light" />
            {/* Header with Logo/Title */}
            <View className="h-[30%] flex-column justify-center items-center">
                <View className="bg-white rounded-full w-32 h-32 justify-center items-center overflow-hidden shadow-lg">
                    <Image
                        source={require('@/assets/images/react-logo.png')}
                        className='h-20 w-20'
                        resizeMode="contain"
                    />
                </View>
            </View>

            {/* Form Container */}
            <View className="flex-1 bg-white rounded-t-[2.5rem] px-8 pt-8 shadow-xl w-full">
                <KeyboardAwareScrollView
                    bottomOffset={Platform.OS === 'ios' ? 50 : 80}
                    keyboardShouldPersistTaps="handled"
                    showsVerticalScrollIndicator={false}
                    contentContainerStyle={{ paddingBottom: 40, flexGrow: 1, justifyContent: 'space-between' }}
                    className="flex-1"
                >
                    <View className="flex-1 flex-col justify-between">
                        <View>
                            <Text className="text-primary-dark text-5xl font-bold text-center mb-3">Accedi</Text>
                            <Text className="text-base font-semibold text-center text-text-secondary mb-10">
                                Inserisci le tue credenziali per accedere
                            </Text>

                            <View className="gap-6 flex flex-col" style={{ gap: '1.5rem' }}>
                                {/* Input Username */}
                                <View>
                                    <View className="flex-row items-center bg-gray-50 border border-gray-100 rounded-2xl h-16 px-4 flex">
                                        <User size={24} color="#9ca3af" pointerEvents="none" />
                                        <TextInput
                                            className="flex-1 ml-4 text-gray-800 text-lg font-medium h-full w-full"
                                            placeholder="Username"
                                            placeholderTextColor="#9ca3af"
                                            value={username}
                                            onChangeText={setUsername}
                                            autoCapitalize="none"
                                        />
                                    </View>
                                </View>

                                {/* Input Password */}
                                <View>
                                    <View className="flex-row items-center bg-gray-50 border border-gray-100 rounded-2xl h-16 px-4 flex">
                                        <Lock size={24} color="#9ca3af" pointerEvents="none" />
                                        <TextInput
                                            className="flex-1 ml-4 text-gray-800 text-lg font-medium h-full w-full"
                                            placeholder="Password"
                                            placeholderTextColor="#9ca3af"
                                            value={password}
                                            onChangeText={setPassword}
                                            secureTextEntry={!showPassword}
                                        />
                                        <TouchableOpacity onPress={() => setShowPassword(!showPassword)}>
                                            {showPassword ? (
                                                <EyeOff size={24} color="#6b7280" pointerEvents="none" />
                                            ) : (
                                                <Eye size={24} color="#6b7280" pointerEvents="none" />
                                            )}
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </View>
                        </View>

                        {/* Login Button */}
                        <View className="mt-8">
                            <TouchableOpacity
                                onPress={handleLogin}
                                activeOpacity={0.8}
                                className={`bg-primary h-16 rounded-2xl flex-row justify-center items-center shadow-md flex ${isLoading ? 'opacity-70' : ''}`}
                                disabled={isLoading}
                            >
                                <Text className="text-white text-xl font-bold mr-2">
                                    {isLoading ? 'ACCESSO IN CORSO...' : 'LOGIN'}
                                </Text>
                                {!isLoading && <LogIn size={24} color="white" pointerEvents="none" />}
                            </TouchableOpacity>
                        </View>
                    </View>
                </KeyboardAwareScrollView>
            </View>
        </View>
    );
}