import { View, Text, StyleSheet, Pressable, Alert } from 'react-native';
import { useEffect, 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 PhoneInput from '../../../global/phone_input';
import * as SecureStore from 'expo-secure-store';
import { usePushNotifications } from '../../../../app/hooks/usePushNotifications';
import { useTranslation } from '../../../../util/hooks/useTranslation';

const BindingPhoneNumberPageStepTwo = ({ bindingFormData, setBindingFormData, setScreen }: any) => {
    const { t } = useTranslation(); // 使用翻译钩子
    const [error, setError] = useState('');
    const [lockEmailInput, setLockEmailInput] = useState(false);
    const [isLoading2, setIsLoading2] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const { expoPushToken } = usePushNotifications();
    
    useEffect(() => {
        let timer: NodeJS.Timeout;
        if (countdown > 0) {
            timer = setInterval(() => {
                setCountdown((prev) => prev - 1);
            }, 1000);
        } else {
            setLockEmailInput(false); // Add this line to unlock input when countdown reaches 0
        }
        return () => {
            if (timer) clearInterval(timer);
        };
    }, [countdown]);
    
    const handleConfirmBindingPhone = async () => {
        setIsLoading2(true);
        try {
            const result = await authenticationService.confirmBindingPhone(
                bindingFormData.phoneNumber,
                bindingFormData.otp,
                expoPushToken?.data ||
                    `ExponentPushToken[TestToken${Math.random().toString(36).substring(2, 8).toUpperCase()}]`
            );

            if (result.status == 200) {
                setScreen(2);
            } else {
                setError(t('binding.two.phone_binding_failed'));
            }
        } catch (error) {
            Alert.alert(t('binding.two.phone_binding_failed'));
        } finally {
            setIsLoading2(false);
        }
    };
    
    const handleRequestOtp = async () => {
        try {
            //this check if phone same,
            const checkPhoneSame = await authenticationService.checkPhoneSame(bindingFormData.phoneNumber);
            if (checkPhoneSame?.status == 422) {
                //this means phone not same
                Alert.alert(t('binding.two.confirm_phone_number'), t('binding.two.phone_usage_notice'), [
                    {
                        text: t('binding.two.confirm_and_send_otp'),
                        onPress: async () => {
                            try {
                                const token = await SecureStore.getItemAsync('accessToken');
                                const changePhoneResult = await authenticationService.changePhone(
                                    bindingFormData.phoneNumber,
                                    token
                                );

                                if (changePhoneResult == true) {
                                    //this means change phone success
                                    try {
                                        const requestOtp = await authenticationService.checkPhoneSame(
                                            bindingFormData.phoneNumber
                                        );

                                        if (requestOtp.status == 200) {
                                            //this means request otp success
                                            setLockEmailInput(true);
                                            setCountdown(60);
                                        } else {
                                            setError(t('binding.two.send_otp_failed'));
                                        }
                                    } catch (error) {}
                                } else {
                                    //this means change phone failed
                                    Alert.alert(t('binding.two.change_phone_failed'));
                                }
                            } catch (error) {}
                        }
                    }
                ]);
            } else {
                //this means phone same
                if (checkPhoneSame?.status == 200) {
                    //this means request otp success
                    setLockEmailInput(true);
                    setCountdown(60); // Start 60 second countdown
                } else {
                    setError(t('binding.two.send_otp_failed'));
                }
            }
        } catch (error) {}
    };

    return (
        <>
            <View style={styles.container}>
                <View style={styles.bottomContainer}>
                    <Text style={styles.text}>{t('binding.two.enter_phone_for_login')}</Text>
                    <PhoneInput
                        value={bindingFormData?.phoneNumber || ''}
                        onChangeText={(phoneNumber) => {
                            setBindingFormData({
                                ...bindingFormData,
                                phoneNumber: phoneNumber
                            });
                        }}
                        placeholder={t('binding.two.enter_phone_number')}
                        editable={!lockEmailInput}
                        extendedStyle={{ opacity: !lockEmailInput ? 1 : 0.5 }}
                    />
                    <View
                        style={{
                            display: 'flex',
                            flexDirection: 'row',
                            paddingVertical: 10,
                            gap: 10
                        }}
                    >
                        <NumberInput
                            placeholder={t('binding.two.otp_verification_code')}
                            onChangeText={(t) => setBindingFormData({ ...bindingFormData, otp: t })}
                            extendedStyle={{
                                flex: 1
                            }}
                        />
                        <NormalButton
                            title={
                                <Text style={{ color: '#fff' }}>
                                    {lockEmailInput ? `${t('binding.two.sent')} (${countdown}s)` : t('binding.two.send')}
                                </Text>
                            }
                            onPress={handleRequestOtp}
                            extendedStyle={{ flex: 1 / 2, opacity: lockEmailInput ? 0.5 : 1 }}
                            disabled={lockEmailInput}
                        />
                    </View>
                    <NormalButton
                        title={<Text style={{ color: '#fff' }}>{isLoading2 ? t('binding.two.processing') : t('binding.two.confirm')}</Text>}
                        onPress={handleConfirmBindingPhone}
                    />

                    {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 BindingPhoneNumberPageStepTwo;