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';
import { useTranslation } from '../../util/hooks/useTranslation';

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 { t } = useTranslation();

    const dropdownOption = [
        { label: t('accountSettings.change_gender.male'), value: 'man' },
        { label: t('accountSettings.change_gender.female'), value: 'woman' }
    ];

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

    const handleChangeGender = async () => {
        if (!gender) {
            setError(t('accountSettings.change_gender.select_gender_error'));
            return;
        }
        if (!token) {
            setError(t('accountSettings.change_gender.no_token_error'));
            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(t('accountSettings.change_gender.update_failed'));
            }
        } catch (error) {
            console.error('Error changing gender:', error);
            setError(t('accountSettings.change_gender.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_gender.change_gender_title')}
                    </Text>
                    <Text className="text-xl ">{t('accountSettings.change_gender.select_new_gender')}</Text>
                    <View className="py-2">
                        <View className="flex-1 ">
                            <DropdownSelect
                                dropdownOptions={dropdownOption}
                                placeholder={t('accountSettings.change_gender.gender')}
                                onSelect={(t) => {
                                    setGender(t);
                                }}
                                extendedStyle={{ width: '100%', padding: 10 }}
                            />
                        </View>
                    </View>
                    <NormalButton
                        title={
                            <Text className="text-white text-lg">
                                {isLoading ? t('accountSettings.change_gender.changing') : t('common.confirm')}
                            </Text>
                        }
                        onPress={handleChangeGender}
                        disabled={isLoading}
                    />
                    {error && (
                        <Text style={{ color: 'red', marginTop: 10 }}>
                            {error}
                        </Text>
                    )}
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChangeGenderPageComponent;