import { View, Text, StyleSheet, TextInput, Pressable } from 'react-native';
import { useEffect, useState } from 'react';
import PhoneInput from '../../../global/phone_input';
import NumberInput from '../../../global/number_input';
import NormalButton from '../../../global/normal_button';
import useSignUpStore from '../../../../providers/signup_form_store';
import { authenticationService } from '../../../../service/authService';
import { usePushNotifications } from '../../../../app/hooks/usePushNotifications';
import { useTranslation } from '../../../../util/hooks/useTranslation';

type VerificationProps = {
    setScreen: React.Dispatch<React.SetStateAction<number>>;
};

const Verification: React.FC<VerificationProps> = ({ setScreen }) => {
    const { signUpFormData, setSignUpFormData } = useSignUpStore();
    const [error, setError] = useState('');
    const [otp, setOtp] = useState('');
    const [canSendOtp, setCanSendOtp] = useState(true);
    const [lockPhoneInput, setLockPhoneInput] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [loading, setLoading] = useState(false);
    const { expoPushToken } = usePushNotifications();
    const { t, ready, currentLanguage } = useTranslation();
    
    const handleVerification = async () => {
        setLoading(true);
        if (signUpFormData.phone === '' || otp === '') {
            setError(t("register.two.error1"));
        } else {
            setError('');
            console.log('signUpFormData.phone', signUpFormData.phone);
            console.log('otp', otp);
            console.log('notifysession id in handleVerification', expoPushToken?.data);
            try {
                const result = await authenticationService.verifyPhoneOtp(
                    signUpFormData.phone as string,
                    otp,
                    expoPushToken?.data as string
                );
                if (result.status === 200) {
                    setScreen(2);
                } else {
                    setError(t("register.two.error2"));
                }
            } catch (error) {
                console.log('error', error);
                setError(t("register.two.error2"));
            } finally {
                setLoading(false);
            }
        }
    };
    useEffect(() => {
        let timer: NodeJS.Timeout;
        if (countdown > 0) {
            timer = setInterval(() => {
                setCountdown((prev) => prev - 1);
            }, 1000);
        } else {
            setLockPhoneInput(false); // Add this line to unlock input when countdown reaches 0
        }
        return () => {
            if (timer) clearInterval(timer);
        };
    }, [countdown]);
    const handleSubmitOtp = async () => {
        if (signUpFormData.phone) {
            if (canSendOtp) {
                setCanSendOtp(false);
                setLockPhoneInput(true);
                setCountdown(60);
                try {
                    await authenticationService.sendOtpToSignUpPhone(signUpFormData.phone);
                    setError('');
                } catch (error) {
                    console.log(error);
                    setError(t("register.two.error3"));
                    setCanSendOtp(true); // Reset canSendOtp if there's an error
                    setLockPhoneInput(false); // Unlock phone input if there's an error
                }
                setTimeout(() => {
                    setCanSendOtp(true);
                    setLockPhoneInput(false);
                }, 60000);
                // setError('');
            } else {
                setError(t("register.two.error4"));
            }
        } else {
            setError(t("register.two.error5"));
        }
    };

    const otpButtonText = lockPhoneInput ? (
        <Text style={{ color: '#fff' }}>{t("register.two.spending")} ({countdown}s)</Text>
    ) : (
        <Text style={{ color: '#fff' }}>{t("register.two.spend")}</Text>
    );

    return (
        <View style={styles.container}>
            <Text style={styles.text}>{t('register.two.label')}</Text>
            <PhoneInput
                value={signUpFormData?.phone || ''}
                onChangeText={(phone: any) =>
                    setSignUpFormData({
                        ...signUpFormData,
                        phone: phone
                    })
                }
                placeholder={t('register.two.phone')}
                editable={!lockPhoneInput}
                extendedStyle={{ opacity: !lockPhoneInput ? 1 : 0.5 }}
            />
            <View
                style={{
                    display: 'flex',
                    flexDirection: 'row',
                    paddingVertical: 10,
                    gap: 10
                }}
            >
                <NumberInput placeholder={t('register.two.code')} onChangeText={setOtp} extendedStyle={{ flex: 1 }} />
                <NormalButton
                    title={otpButtonText}
                    onPress={handleSubmitOtp}
                    extendedStyle={{ flex: 1 / 2, opacity: !lockPhoneInput ? 1 : 0.5 }}
                />
            </View>
            <NormalButton
                title={<Text style={{ color: '#fff' }}>{loading ? t('register.two.verifying') : t('register.two.verify')}</Text>}
                onPress={() => {
                    handleVerification();
                }}
            />
            {error && <Text style={styles.errorMessage}>{error}</Text>}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginHorizontal: 20
    },
    text: {
        fontSize: 20,
        paddingBottom: 10
    },
    errorMessage: {
        fontSize: 16,
        color: '#ff0033',
        fontWeight: '400',

        paddingVertical: 10
    },
    footer: { color: '#02677D', fontSize: 16, paddingVertical: 10 }
});
export default Verification;
