import { View, Text, ScrollView, StyleSheet, Pressable } from 'react-native';
import { 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';
import { useTranslation } from '../../util/hooks/useTranslation';

const changePasswordPageComponent = () => {
    const { user, setUser } = useContext(AuthContext);
    const [token, setToken] = useState<string | null>(null);
    const [currentPassword, setCurrentPassword] = useState<string | null>(null);
    const [newPassword, setNewPassword] = useState<string | null>(null);
    const [newConfirmPassword, setNewConfirmPassword] = useState<string | null>(null);
    const [isPasswordVerified, setIsPasswordVerified] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);
    const [isLoading2, setIsLoading2] = useState(false);
    const { t } = useTranslation();

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

    const handleVerifyPassword = async (currentPassword: string) => {
        try {
            setIsLoading(true);
            if (!currentPassword) {
                setError(t('accountSettings.change_password.enter_password_error'));
                return;
            }
            if (!user || !user.email) {
                setError(t('accountSettings.change_password.user_verification_error'));
                return;
            }

            const success = await authenticationService.phoneLogin(user.phone, currentPassword);
            if (success) {
                setIsPasswordVerified(true);
                setError('');
                return true;
            } else {
                setError(t('accountSettings.change_password.incorrect_password'));
            }
        } catch (error) {
            console.error('Error verifying password:', error);
            setError(t('accountSettings.change_password.incorrect_password'));
            return false;
        } finally {
            setIsLoading(false);
        }
    };

    const handlePasswordChange = async () => {
        try {
            setIsLoading2(true);
            if (newPassword !== newConfirmPassword) {
                setError(t('accountSettings.change_password.password_mismatch'));
                return;
            }

            if (!newConfirmPassword || !token) {
                setError(t('accountSettings.change_password.enter_new_password'));
                return;
            }

            const success = await authenticationService.changePassword(newConfirmPassword, token);

            if (success) {
                setError('');
                router.replace('accountMainPage');
            } else {
                setError(t('accountSettings.change_password.change_password_failed'));
            }
        } catch (error) {
            console.error('Error changing password:', error);
            setError(t('accountSettings.change_password.general_error'));
        } finally {
            setIsLoading2(false);
        }
    };

    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
            <ScrollView className="flex-1 mx-[5%]" showsVerticalScrollIndicator={false}>
                <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_password.change_password_title')}</Text>
                    <Text className="text-xl ">{t('accountSettings.change_password.enter_current_password')}</Text>
                    <View className="py-2">
                        <NormalInput
                            placeholder={t('accountSettings.change_password.account_password')}
                            onChangeText={(t) => setCurrentPassword(t)}
                            secureTextEntry={true}
                            editable={!isPasswordVerified}
                        />
                    </View>

                    <NormalButton
                        title={
                            <Text style={{ color: '#fff' }}>
                                {isLoading ? t('accountSettings.change_password.verifying') : isPasswordVerified ? t('accountSettings.change_password.verified') : t('common.next')}
                            </Text>
                        }
                        onPress={() => {
                            if (currentPassword) {
                                handleVerifyPassword(currentPassword);
                            }
                        }}
                        disabled={isPasswordVerified}
                        extendedStyle={isPasswordVerified == true ? { backgroundColor: '#70787C' } : {}}
                    />
                </View>

                {isPasswordVerified && (
                    <View
                        style={[
                            styles.hiddenPasswordFields,
                            isPasswordVerified ? styles.opacityFull : styles.opacityZero
                        ]}
                    >
                        <NormalInput
                            placeholder={t('accountSettings.change_password.new_password')}
                            onChangeText={(t) => setNewPassword(t)}
                            secureTextEntry={true}
                            textContentType={'oneTimeCode'}
                        />
                        <NormalInput
                            placeholder={t('accountSettings.change_password.confirm_password')}
                            onChangeText={(t) => setNewConfirmPassword(t)}
                            secureTextEntry={true}
                            textContentType={'oneTimeCode'}
                        />
                        <NormalButton
                            title={<Text style={{ color: '#fff' }}>{isLoading2 ? t('accountSettings.change_password.changing') : t('common.confirm')}</Text>}
                            onPress={handlePasswordChange}
                        />
                    </View>
                )}

                {error && <Text style={styles.errorMessage}>{error}</Text>}
            </ScrollView>
        </SafeAreaView>
    );
};

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 }
});

export default changePasswordPageComponent;