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 NormalButton from '../global/normal_button';
import * as SecureStore from 'expo-secure-store';
import { authenticationService } from '../../service/authService';
import DropdownSelect from '../global/dropdown_select';

const ChangeGenderPageComponent = () => {
    const { user, setUser } = useContext(AuthContext);
    const [token, setToken] = useState<string | null>(null);
    const [gender, setGender] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const dropdownOption = [
        { label: '男', value: 'man' },
        { label: '女', value: 'woman' }
    ];

    useEffect(() => {
        const getToken = async () => {
            const storedToken = await SecureStore.getItemAsync('accessToken');
            setToken(storedToken);
        };
        getToken();
    }, []);
    const handleChangeGender = async () => {
        if (!gender) {
            setError('請選擇性別');
            return;
        }
        if (!token) {
            setError('未找到有效的登錄令牌，請重新登錄');
            return;
        }
        setError(null);
        setIsLoading(true);
        try {
            const success = await authenticationService.changeGender(
                gender,
                token
            );
            if (success) {
                if (user) {
                    setUser({
                        ...user,
                        gender: gender
                    });
                }
                router.replace('accountMainPage');
            } else {
                setError('更新性別失敗，請稍後再試');
            }
        } catch (error) {
            console.error('Error changing gender:', 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">
                        <View className="flex-1 ">
                            <DropdownSelect
                                dropdownOptions={dropdownOption}
                                placeholder="性別"
                                onSelect={(t) => {
                                    setGender(t);
                                }}
                                extendedStyle={{ width: '100%', padding: 10 }}
                            />
                        </View>
                    </View>
                    <NormalButton
                        title={
                            <Text className="text-white text-lg">
                                {isLoading ? '更改中...' : '確認'}
                            </Text>
                        }
                        onPress={handleChangeGender}
                        disabled={isLoading}
                    />
                    {error && (
                        <Text style={{ color: 'red', marginTop: 10 }}>
                            {error}
                        </Text>
                    )}
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChangeGenderPageComponent;
