import { View, Text, StyleSheet, ActivityIndicator, Pressable } from 'react-native';
import NormalInput from '../../../global/normal_input';
import NormalButton from '../../../global/normal_button';
import { Ionicons } from '@expo/vector-icons';
import { useState } from 'react';
import SingleSelectButtonGroup from '../../../global/select_button';
import useSignUpStore from '../../../../providers/signup_form_store';
import PhoneInput from '../../../global/phone_input';
import { authenticationService } from '../../../../service/authService';
import { Alert } from 'react-native';
import useVehicleStore from '../../../../providers/vehicle_store';
import { usePushNotifications } from '../../../../app/hooks/usePushNotifications';
type CreateWalletProps = {
    goToNextPage: () => void;
};
const creditCard = '信用卡';
const weChatAliPay = '微信支付/支付寶';

const CreateWallet: React.FC<CreateWalletProps> = ({ goToNextPage }) => {
    const { expoPushToken } = usePushNotifications();
    const options = [{ label: creditCard }, { label: weChatAliPay }];
    const [isLoading, setIsLoading] = useState(false);
    const [isLoading2, setIsLoading2] = useState(false);
    const { signUpFormData, setSignUpFormData } = useSignUpStore();
    const phoneFieldPlaceholder = signUpFormData.phone ? signUpFormData.phone : '輸入電話號碼';
    const [error, setError] = useState('');
    const [showPassword1, setShowPassword1] = useState(false);
    const [showPassword2, setShowPassword2] = useState(false);
    const [passwordConfirm, setPasswordConfirm] = useState('');
    const {
        vehicleBrand,
        vehicleModel,
        BrandID,
        ModelID,
        licensePlate,
        setVehicleBrand,
        setVehicleModel,
        setBrandID,
        setModelID,
        setLicensePlate
    } = useVehicleStore();

    // console.log('expoPushToken?.data', expoPushToken?.data);

    let customerData: any = {
        customerBaseInfo: {
            name: signUpFormData.nickName.trim(),
            email: signUpFormData.email,
            password: signUpFormData.password,
            gender: signUpFormData.gender,
            birthday: signUpFormData.birthDateDay + '/' + signUpFormData.birthDateMonth + '/11',
            address: signUpFormData.address,
            phone: parseInt(signUpFormData.phone, 10),
            isUberDriver: signUpFormData.isUberDriver,
            notify_session_id: expoPushToken?.data
        }
    };
    if (ModelID !== '' && BrandID !== '' && signUpFormData.licensePlate !== '') {
        customerData.customerCarInfo = {
            type_id: ModelID,
            brand_id: BrandID,
            licensePlate: signUpFormData.licensePlate
        };
    }

    const selectLabelShown = () => {
        if (signUpFormData.paymentMethod == null) {
            return null;
        } else if (signUpFormData.paymentMethod == creditCard) {
            return creditCard;
        } else if (signUpFormData.paymentMethod == weChatAliPay) {
            return weChatAliPay;
        }
    };

    const handleSelectedChange = (selectedLabel: string) => {
        setSignUpFormData({ ...signUpFormData, paymentMethod: selectedLabel });
        setError('');
    };

    const handleNextWithSkip = async () => {
        setIsLoading2(true);
        try {
            const result = await authenticationService.signUp(customerData);
            console.log('handleNextWithSkip in CreateWallet Page, i am sending this customerData', customerData);
            if (result === true) {
                goToNextPage();
            } else {
                Alert.alert('註冊錯誤', '註冊過程中出現錯誤，請稍後再試');
            }
        } catch (error) {
            console.error('Sign up error:', error);
            setError('註冊過程中出現錯誤，請稍後再試。');
        } finally {
            setIsLoading2(false);
        }
    };

    const handleNext = async () => {
        if (
            signUpFormData.email === '' ||
            signUpFormData.password === '' ||
            signUpFormData.phone === '' ||
            passwordConfirm === ''
        ) {
            setError('請確保所有資料都已填寫。');
        } else if (signUpFormData.password !== passwordConfirm) {
            Alert.alert('密碼錯誤', '兩次輸入的密碼不一致，請重新輸入。');
        } else {
            setError('');
            setIsLoading(true);
            try {
                const result = await authenticationService.signUp(customerData);
                console.log('handleNext in CreateWallet Page, i am sending this customerData', customerData);
                if (result) {
                    goToNextPage();
                } else {
                    Alert.alert('註冊錯誤', '註冊過程中出現錯誤，請稍後再試');
                }
            } catch (error) {
                setError('註冊過程中出現錯誤，請稍後再試。');
                console.error('Sign up error:', error);
            } finally {
                setIsLoading(false);
            }
        }
    };

    return (
        <>
            <View style={styles.container}>
                <Text style={styles.text}>請填妥以下資料</Text>
                <View
                    style={{
                        display: 'flex',
                        flexDirection: 'column',
                        gap: 10
                    }}
                >
                    <NormalInput
                        placeholder="請填寫您的電子郵件"
                        onChangeText={(email) =>
                            setSignUpFormData({
                                ...signUpFormData,
                                email: email
                            })
                        }
                        autoCapitalize="none"
                    />

                    <NormalInput
                        placeholder="帳戶密碼"
                        onChangeText={(text) => {
                            setSignUpFormData({
                                ...signUpFormData,
                                password: text
                            });
                        }}
                        secureTextEntry={!showPassword1}
                    />
                    <Pressable
                        className="absolute right-4 top-0 bottom-0 justify-center"
                        onPress={() => setShowPassword1(!showPassword1)}
                    >
                        <Ionicons name={showPassword1 ? 'eye-outline' : 'eye-off-outline'} size={24} color="#02677D" />
                    </Pressable>
                    <View className="mb-4">
                        <NormalInput
                            placeholder="請再次輸入帳戶密碼"
                            onChangeText={(text) => setPasswordConfirm(text)}
                            secureTextEntry={!showPassword2}
                        />
                        <Pressable
                            className="absolute right-4 top-0 bottom-0 justify-center"
                            onPress={() => setShowPassword2(!showPassword2)}
                        >
                            <Ionicons
                                name={showPassword2 ? 'eye-outline' : 'eye-off-outline'}
                                size={24}
                                color="#02677D"
                            />
                        </Pressable>
                    </View>
                    {/* <SingleSelectButtonGroup
                        options={options}
                        onSelectionChange={handleSelectedChange}
                        selectedOption={selectLabelShown()}
                    /> */}
                </View>
                {error && <Text style={styles.errorMessage}>{error}</Text>}
                <View>
                    <NormalButton
                        title={isLoading ? <ActivityIndicator /> : <Text style={{ color: '#fff' }}>完成</Text>}
                        onPress={handleNext}
                        extendedStyle={{}}
                    />
                    {/* 收起按鈕 */}
                    {/* <NormalButton
                        title={isLoading2 ? <ActivityIndicator /> : <Text style={{ color: '#888888' }}>略過</Text>}
                        onPress={handleNextWithSkip}
                        extendedStyle={{ backgroundColor: 'transparent' }}
                        buttonPressedStyle={{ backgroundColor: 'transparent' }}
                    /> */}
                </View>
            </View>
        </>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginHorizontal: 20
    },
    text: {
        fontSize: 20,
        paddingBottom: 10
    },
    errorMessage: {
        fontSize: 14,
        color: '#ff0033',
        fontWeight: '400',
        marginLeft: 10,
        marginBottom: 10
    }
});
export default CreateWallet;
