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 NormalInput from '../../../global/normal_input';
import { authenticationService } from '../../../../service/authService';
import { usePushNotifications } from '../../../../app/hooks/usePushNotifications';

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 notify_session_id = expoPushToken?.data || '';
    const handleVerification = async () => {
        setLoading(true);
        if (signUpFormData.phone === '' || otp === '') {
            setError('請確保所有資料都已填寫。');
        } 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,
                    otp,
                    expoPushToken?.data
                );
                if (result.status === 200) {
                    setScreen(2);
                } else {
                    setError('OTP驗證失敗，請重新輸入');
                }
            } catch (error) {
                console.log('error', error);
                setError('OTP驗證失敗，請重新輸入');
            } 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 = () => {
        if (signUpFormData.phone) {
            if (canSendOtp) {
                setCanSendOtp(false);
                setLockPhoneInput(true);
                setCountdown(60);
                authenticationService.sendOtpToSignUpPhone(signUpFormData.phone);
                setTimeout(() => {
                    setCanSendOtp(true);
                    setLockPhoneInput(false);
                }, 60000);
                setError('');
            } else {
                setError('請等待一分鐘後再重新發送。');
            }
        } else {
            setError('請確保所有資料都已填寫。');
        }
    };

    const handleChangePhoneNumber = () => {
        setLockPhoneInput(false);
    };

    const otpButtonText = lockPhoneInput ? (
        <Text style={{ color: '#fff' }}>已發送 ({countdown}s)</Text>
    ) : (
        <Text style={{ color: '#fff' }}>發送</Text>
    );

    return (
        <>
            <View style={styles.container}>
                <Text style={styles.text}>請驗證您的手機號碼</Text>

                <PhoneInput
                    value={signUpFormData?.phone || ''}
                    onChangeText={(phone: any) =>
                        setSignUpFormData({
                            ...signUpFormData,
                            phone: phone
                        })
                    }
                    placeholder="請輸入手機號碼"
                    editable={!lockPhoneInput}
                    extendedStyle={{ opacity: !lockPhoneInput ? 1 : 0.5 }}
                />
                {/* <NormalInput
                    placeholder="請填寫您的手機號碼"
                    onChangeText={(phone) =>
                        setSignUpFormData({
                            ...signUpFormData,
                            phone: phone
                        })
                    }
                    editable={!lockPhoneInput}
                    extendedStyle={{ opacity: !lockPhoneInput ? 1 : 0.5 }}
                    autoCapitalize="none"
                /> */}

                <View
                    style={{
                        display: 'flex',
                        flexDirection: 'row',
                        paddingVertical: 10,
                        gap: 10
                    }}
                >
                    <NumberInput placeholder="OTP驗證碼" 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 ? '驗證中...' : '驗證'}</Text>}
                    onPress={() => {
                        handleVerification();
                    }}
                    extendedStyle={{}}
                />
                {error && <Text style={styles.errorMessage}>{error}</Text>}

                {/* <Pressable onPress={handleChangePhoneNumber}>
                    <Text style={[styles.footer, { opacity: lockPhoneInput ? 1 : 0 }]}>修改手機號碼</Text>
                </Pressable> */}
            </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;
