import { View, Text, ScrollView, Pressable, StyleSheet } 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 * as SecureStore from 'expo-secure-store';
import { authenticationService } from '../../service/authService';

const ChangePhonePageComponent = () => {
    const { user, setUser } = useContext(AuthContext);
    const [token, setToken] = useState<string | null>(null);
    const [phone, setPhone] = 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 handleChangePhone = async () => {
        if (!phone) {
            setError('請輸入新的電話號碼');
            return;
        }
        if (!token) {
            setError('未找到有效的登錄令牌，請重新登錄');
            return;
        }
        setError(null);
        setIsLoading(true);
        try {
            const success = await authenticationService.changePhone(
                phone,
                token
            );
            if (success) {
                if (user) {
                    setUser({
                        ...user,
                        phone: phone
                    });
                }
                router.replace('accountMainPage');
            } else {
                setError('更新電話號碼失敗，請稍後再試');
            }
        } catch (error) {
            console.error('Error changing phone:', 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="請輸入新的電話號碼"
                            onChangeText={(t) => {
                                setPhone(t);
                            }}
                            editable={!isLoading}
                        />
                    </View>
                    <NormalButton
                        title={
                            <Text className="text-white">
                                {isLoading ? '更改中...' : '確認'}
                            </Text>
                        }
                        onPress={handleChangePhone}
                        disabled={isLoading}
                    />
                    {error && (
                        <Text style={{ color: 'red', marginTop: 10 }}>
                            {error}
                        </Text>
                    )}
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChangePhonePageComponent;

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginHorizontal: 20
    },

    titleText: {
        fontSize: 24,
        fontWeight: '300'
    },
    bottomContainer: {
        flex: 3,
        paddingBottom: 100
    },
    breakline: {
        width: 24,
        height: 1,
        backgroundColor: '#000000',
        marginVertical: 17
    },
    text: {
        fontSize: 18,
        paddingBottom: 10
    },
    hiddenPasswordFields: {
        gap: 10,
        paddingTop: 10
    },
    opacityZero: {
        opacity: 0
    },
    opacityFull: {
        opacity: 1
    },
    errorMessage: {
        fontSize: 14,
        color: '#ff0033',
        fontWeight: '400',
        marginLeft: 10,
        marginTop: 10
    },
    footer: { color: '#02677D', fontSize: 16, paddingVertical: 10 }
});
