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';
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);
    useEffect(() => {
        const getToken = async () => {
            const storedToken = await SecureStore.getItemAsync('accessToken');
            setToken(storedToken);
        };
        getToken();
    }, []);

    const handleChangeName = async () => {
        if (!name) {
            setError('請輸入新的暱稱');
            return;
        }
        if (!token) {
            setError('未找到有效的登錄令牌，請重新登錄');
            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('更新暱稱失敗，請稍後再試');
            }
        } catch (error) {
            console.error('Error changing name:', error);
            setError('發生錯誤，請稍後再試');
        } 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 }}>
                        更改暱稱
                    </Text>
                    <Text className="text-xl ">請輸入新名稱</Text>
                    <View className="py-2">
                        <NormalInput
                            placeholder={user?.nickname}
                            onChangeText={(t) => setName(t)}
                            editable={!isLoading}
                        />
                    </View>
                    <NormalButton
                        title={
                            <Text className="text-white">
                                {isLoading ? '更改中...' : '確認'}
                            </Text>
                        }
                        disabled={isLoading}
                        onPress={handleChangeName}
                    />
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChangeNamePageComponent;
