import { View, Text, StyleSheet, Pressable } from 'react-native';
import { useState } from 'react';
import { forgetPasswordFormData, HandleForgetPasswordFormDataChange } from '../../../../types/signup';
import NumberInput from '../../../global/number_input';
import NormalButton from '../../../global/normal_button';
import NormalInput from '../../../global/normal_input';
import { authenticationService } from '../../../../service/authService';
import { useTranslation } from '../../../../util/hooks/useTranslation';

type ForgetPasswordPageProps = {
    forgetPasswordFormData: forgetPasswordFormData;
    setForgetPasswordFormData: React.Dispatch<React.SetStateAction<forgetPasswordFormData>>;
    setScreen: React.Dispatch<React.SetStateAction<number>>;
};

const ForgetPasswordPage: React.FC<ForgetPasswordPageProps> = ({
    forgetPasswordFormData,
    setForgetPasswordFormData,
    setScreen
}) => {
    const { t } = useTranslation(); // 使用翻译钩子
    const [authError, setAuthError] = useState('');
    const [error, setError] = useState('');
    const [canSendOtp, setCanSendOtp] = useState(true);
    const [lockEmailInput, setLockEmailInput] = useState(false);
    const [data, setData] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [isLoading2, setIsLoading2] = useState(false);

    const handleVerification = async () => {
        setIsLoading(true);
        if (!forgetPasswordFormData.otp && !forgetPasswordFormData.email) {
            setAuthError(t('forgotPassword.one.ensure_all_fields_filled'));
        } else if (!forgetPasswordFormData.otp) {
            setAuthError(t('forgotPassword.one.enter_otp_code'));
        } else {
            setAuthError('');
            try {
                const result = await authenticationService.verifyingOtpForgetPassword(
                    forgetPasswordFormData.email,
                    forgetPasswordFormData.otp,
                    setForgetPasswordFormData,
                    setData
                );
                if (result === false) {
                    setAuthError(t('forgotPassword.one.error_verifying_otp'));
                }
            } catch (error) {
                console.error('Error verifying OTP:', error);
                setAuthError(t('forgotPassword.one.error_verifying_otp'));
            }
        }
        setIsLoading(false);
    };

    const handleFormDataChange: HandleForgetPasswordFormDataChange = (field, value) => {
        setForgetPasswordFormData((prevFormData) => ({
            ...prevFormData,
            [field]: value
        }));
    };

    const handleSubmitOtp = () => {
        if (forgetPasswordFormData.email) {
            if (canSendOtp) {
                const email = forgetPasswordFormData.email;
                setCanSendOtp(false);
                setLockEmailInput(true);
                authenticationService.sendForgetPasswordOtp(email);
                //can only request otp every 60 seconds
                setTimeout(() => {
                    setCanSendOtp(true);
                    setLockEmailInput(false);
                }, 60000);
                setAuthError('');
            } else {
                setAuthError(t('forgotPassword.one.wait_one_minute'));
            }
        } else {
            setAuthError(t('forgotPassword.one.ensure_all_fields_filled'));
        }
    };

    const handleFinishResetPassword = async () => {
        if (forgetPasswordFormData.newPassword !== forgetPasswordFormData.confirmedNewPassword) {
            setError(t('forgotPassword.one.passwords_do_not_match'));
        } else {
            setError('');
            setIsLoading2(true);
            try {
                const success = await authenticationService.changePassword(
                    forgetPasswordFormData.confirmedNewPassword,
                    data
                );
                if (success) {
                    setScreen(1);
                } else {
                    setError(t('forgotPassword.one.password_reset_failed'));
                }
            } catch (error) {
                console.error('Error changing password:', error);
                setError(t('forgotPassword.one.error_occurred'));
            } finally {
                setIsLoading2(false);
            }
        }
    };

    return (
        <>
            <View style={styles.container}>
                <View style={styles.bottomContainer}>
                    <Text style={styles.text}>{t('forgotPassword.one.verify_email_to_reset')}</Text>

                    <NormalInput
                        placeholder={t('forgotPassword.one.enter_your_email')}
                        onChangeText={(email) =>
                            setForgetPasswordFormData({
                                ...forgetPasswordFormData,
                                email: email
                            })
                        }
                        editable={!lockEmailInput}
                        extendedStyle={{ opacity: !lockEmailInput ? 1 : 0.5 }}
                        autoCapitalize="none"
                    />
                    <View
                        style={{
                            display: 'flex',
                            flexDirection: 'row',
                            paddingVertical: 10,
                            gap: 10
                        }}
                    >
                        <NumberInput
                            placeholder={t('forgotPassword.one.otp_verification_code')}
                            onChangeText={(t) => handleFormDataChange('otp', t)}
                            editable={!forgetPasswordFormData.otpAuthCompleted}
                            extendedStyle={{
                                flex: 1,
                                opacity: !forgetPasswordFormData.otpAuthCompleted ? 1 : 0.5
                            }}
                        />
                        <NormalButton
                            title={<Text style={{ color: '#fff' }}>{lockEmailInput ? t('forgotPassword.one.sent') : t('forgotPassword.one.send')}</Text>}
                            onPress={handleSubmitOtp}
                            extendedStyle={{ flex: 1 / 2 }}
                        />
                    </View>
                    <NormalButton
                        title={
                            <Text style={{ color: '#fff' }}>
                                {isLoading
                                    ? t('forgotPassword.one.verifying')
                                    : forgetPasswordFormData.otpAuthCompleted == true
                                    ? t('forgotPassword.one.verified')
                                    : t('forgotPassword.one.verify')}
                            </Text>
                        }
                        onPress={handleVerification}
                        extendedStyle={
                            forgetPasswordFormData.otpAuthCompleted == true ? { backgroundColor: '#70787C' } : {}
                        }
                    />

                    {authError && <Text style={styles.errorMessage}>{authError}</Text>}
                    {lockEmailInput && (
                        <Pressable
                            disabled={forgetPasswordFormData.otpAuthCompleted}
                            onPress={() => setLockEmailInput(false)}
                        >
                            <Text
                                style={[
                                    styles.footer,
                                    forgetPasswordFormData.otpAuthCompleted && {
                                        opacity: 0.5
                                    }
                                ]}
                            >
                                {t('forgotPassword.one.modify_email')}
                            </Text>
                        </Pressable>
                    )}

                    {forgetPasswordFormData.otpAuthCompleted && (
                        <View
                            style={[
                                styles.hiddenPasswordFields,
                                forgetPasswordFormData.otpAuthCompleted ? styles.opacityFull : styles.opacityZero
                            ]}
                        >
                            <NormalInput
                                placeholder={t('forgotPassword.one.new_password')}
                                onChangeText={(t) => handleFormDataChange('newPassword', t)}
                                secureTextEntry={true}
                                textContentType={'oneTimeCode'}
                                autoCapitalize="none"
                            />
                            <NormalInput
                                placeholder={t('forgotPassword.one.confirm_password')}
                                onChangeText={(t) => handleFormDataChange('confirmedNewPassword', t)}
                                secureTextEntry={true}
                                textContentType={'oneTimeCode'}
                                autoCapitalize="none"
                            />
                            <NormalButton
                                title={<Text style={{ color: '#fff' }}>{isLoading ? t('forgotPassword.one.resetting') : t('forgotPassword.one.reset')}</Text>}
                                onPress={handleFinishResetPassword}
                                extendedStyle={{}}
                            />
                        </View>
                    )}

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

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 ForgetPasswordPage;