import { View, Text, StyleSheet, Pressable, Alert } from 'react-native';
import { useState } from 'react';
import { Ionicons } from '@expo/vector-icons';
import NumberInput from '../../../global/number_input';
import NormalButton from '../../../global/normal_button';
import NormalInput from '../../../global/normal_input';
import { authenticationService } from '../../../../service/authService';

const BindingPhoneNumberPage = ({ bindingFormData, setBindingFormData, setScreen }: any) => {
    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 [showPassword, setShowPassword] = useState(false);
    // const handleVerification = async () => {
    //     setIsLoading(true);
    //     if (!forgetPasswordFormData.otp && !forgetPasswordFormData.email) {
    //         setAuthError('請確保所有資料都已填寫');
    //     } else if (!forgetPasswordFormData.otp) {
    //         setAuthError('請輸入OTP驗證碼');
    //     } else {
    //         setAuthError('');
    //         try {
    //             const result = await authenticationService.verifyingOtpForgetPassword(
    //                 forgetPasswordFormData.email.toLowerCase(),
    //                 forgetPasswordFormData.otp,
    //                 setForgetPasswordFormData,
    //                 setData
    //             );
    //             if (result === false) {
    //                 setAuthError('驗證OTP時發生錯誤，請稍後再試');
    //             }
    //         } catch (error) {
    //             console.error('Error verifying OTP:', error);
    //             setAuthError('驗證OTP時發生錯誤，請稍後再試');
    //         }
    //     }
    //     setIsLoading(false);
    // };

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

    // const handleSubmitOtp = () => {
    //     if (forgetPasswordFormData.email) {
    //         if (canSendOtp) {
    //             const lowerCaseEmail = forgetPasswordFormData.email.toLowerCase();
    //             setCanSendOtp(false);
    //             setLockEmailInput(true);
    //             authenticationService.sendForgetPasswordOtp(lowerCaseEmail);
    //             //can only request otp every 60 seconds
    //             setTimeout(() => {
    //                 setCanSendOtp(true);
    //                 setLockEmailInput(false);
    //             }, 60000);
    //             setAuthError('');
    //         } else {
    //             setAuthError('請等待一分鐘後再重新發送。');
    //         }
    //     } else {
    //         setAuthError('請確保所有資料都已填寫。');
    //     }
    // };

    // const handleFinishResetPassword = async () => {
    //     if (forgetPasswordFormData.newPassword !== forgetPasswordFormData.confirmedNewPassword) {
    //         setError('請確保新密碼和確認密碼相同');
    //     } else {
    //         setError('');
    //         setIsLoading2(true);
    //         try {
    //             const success = await authenticationService.changePassword(
    //                 forgetPasswordFormData.confirmedNewPassword,
    //                 data
    //             );
    //             if (success) {
    //                 setScreen(1);
    //             } else {
    //                 setError('密碼重置失敗，請稍後再試');
    //             }
    //         } catch (error) {
    //             console.error('Error changing password:', error);
    //             setError('發生錯誤，請稍後再試');
    //         } finally {
    //             setIsLoading2(false);
    //         }
    //     }
    // };

    const handleVerification = async () => {
        setIsLoading(true);
        try {
            const isBinding = true;
            const response = await authenticationService.emailLogin(
                bindingFormData.email,
                bindingFormData.password,
                isBinding
            );

            if (response == true) {
                setScreen(1);
            } else {
                Alert.alert('登入失敗，請檢查您輸入的帳號密碼並再試一次');
            }
        } catch (error) {
        } finally {
            setIsLoading(false);
        }
    };
    return (
        <>
            <View style={styles.container}>
                <View style={styles.bottomContainer}>
                    <Text style={styles.text}>請輸入現有電子郵件</Text>
                    <View className="pb-2">
                        <NormalInput
                            placeholder="請填寫您的電子郵件"
                            onChangeText={(email) =>
                                setBindingFormData({
                                    ...bindingFormData,
                                    email: email
                                })
                            }
                            textContentType="username"
                            autoComplete="username"
                            keyboardType="email-address"
                            autoCapitalize="none"
                        />
                    </View>
                    <View className="pb-2">
                        <NormalInput
                            placeholder="請填寫您的密碼"
                            onChangeText={(password) =>
                                setBindingFormData({
                                    ...bindingFormData,
                                    password: password
                                })
                            }
                            secureTextEntry={!showPassword}
                            extendedStyle={{ borderRadius: 12, padding: 20, paddingRight: 50 }}
                            textContentType="password"
                            autoComplete="password"
                        />
                        <Pressable
                            className="absolute right-4 top-0 bottom-0 justify-center"
                            onPress={() => setShowPassword(!showPassword)}
                        >
                            <Ionicons
                                name={showPassword ? 'eye-outline' : 'eye-off-outline'}
                                size={24}
                                color="#02677D"
                            />
                        </Pressable>
                    </View>
                    <NormalButton
                        title={<Text style={{ color: '#fff' }}>{isLoading ? '處理中...' : '下一步'}</Text>}
                        onPress={handleVerification}
                        // extendedStyle={
                        //     forgetPasswordFormData.otpAuthCompleted == true ? { backgroundColor: '#70787C' } : {}
                        // }
                    />

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