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 ChangeNamePageComponent = () => {
    const { user, setUser } = useContext(AuthContext);
    const [token, setToken] = useState<string | null>(null);
    const [name, 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 handleChangeName = async () => {
        if (!name) {
            setError(t('accountSettings.change_name.enter_new_nickname_error'));
            return;
        }
        if (!token) {
            setError(t('accountSettings.change_name.no_token_error'));
            return;
        }
        setError(null);
        setIsLoading(true);
        try {
            const success = await authenticationService.changeName(name, token);
            if (success) {
                if (user) {
                    setUser({
                        ...user,
                        nickname: name
                    });
                }
                router.replace('accountMainPage');
            } else {
                setError(t('accountSettings.change_name.update_failed'));
            }
        } catch (error) {
            console.error('Error changing name:', error);
            setError(t('accountSettings.change_name.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_name.change_nickname_title')}
                    </Text>
                    <Text className="text-xl ">{t('accountSettings.change_name.enter_new_name')}</Text>
                    <View className="py-2">
                        <NormalInput
                            placeholder={user?.nickname || ''}
                            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_name.changing') : t('common.confirm')}
                            </Text>
                        }
                        disabled={isLoading}
                        onPress={handleChangeName}
                    />
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChangeNamePageComponent;