import { View, Text, ScrollView, Pressable } from 'react-native';
import React, { useContext, useEffect, useState } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { CrossLogoSvg } from '../global/SVG';
import { AuthContext } from '../../context/AuthProvider';
import NormalInput from '../global/normal_input';
import NormalButton from '../global/normal_button';
import { authenticationService } from '../../service/authService';
import * as SecureStore from 'expo-secure-store';
import { useTranslation } from '../../util/hooks/useTranslation';

const ChangeEmailPageComponent = () => {
    const { user, setUser } = useContext(AuthContext);
    const [token, setToken] = useState<string | null>(null);
    const [email, setName] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const { t } = useTranslation();

    useEffect(() => {
        const getToken = async () => {
            const storedToken = await SecureStore.getItemAsync('accessToken');
            setToken(storedToken);
        };
        getToken();
    }, []);

    const handleChangeEmail = async () => {
        if (!email) {
            setError(t('accountSettings.change_email.enter_new_email_error'));
            return;
        }
        if (!token) {
            setError(t('accountSettings.change_email.no_token_error'));
            return;
        }
        setError(null);
        setIsLoading(true);
        try {
            const success = await authenticationService.changeEmail(email, token);
            if (success) {
                if (user) {
                    setUser({
                        ...user,
                        email: email
                    });
                }
                router.replace('accountMainPage');
            } else {
                setError(t('accountSettings.change_email.update_failed'));
            }
        } catch (error) {
            console.error('Error changing name:', error);
            setError(t('accountSettings.change_email.general_error'));
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <SafeAreaView
            className="flex-1 bg-white"
            edges={['top', 'right', 'left']}
        >
            <ScrollView className="flex-1 mx-[5%]">
                <View style={{ marginTop: 25 }}>
                    <Pressable
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/accountMainPage');
                            }
                        }}
                    >
                        <CrossLogoSvg />
                    </Pressable>
                    <Text style={{ fontSize: 45, marginVertical: 25 }}>
                        {t('accountSettings.change_email.change_email_title')}
                    </Text>
                    <Text className="text-xl ">{t('accountSettings.change_email.enter_new_email')}</Text>
                    <View className="py-2">
                        <NormalInput
                            placeholder={user?.email || ''}
                            onChangeText={(t) => setName(t)}
                            editable={!isLoading}
                        />
                    </View>
                    {error && (
                        <Text className="text-red-500 py-2">{error}</Text>
                    )}
                    <NormalButton
                        title={
                            <Text className="text-white">
                                {isLoading ? t('accountSettings.change_email.changing') : t('common.confirm')}
                            </Text>
                        }
                        disabled={isLoading}
                        onPress={handleChangeEmail}
                    />
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChangeEmailPageComponent;