import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Button, Text, TextInput, View } from 'react-native';

import { getEmailAvailability } from '../../../api/profile.js';

import styles from '../Profile.styles.js';

const STRINGS = {
    CONTINUE: 'continue',
    PLACEHOLDER: 'email address',
    REGISTERED: `You've already registered!`,
    RESET_PASSWORD: 'reset password',
};

export default function EmailInput({ email, handleValidEmailEntry, isRequired, showContinueButton }) {
    const [emailValue, setEmail] = useState(email);
    const [isEmailAvailable, setEmailAvailable] = useState(null);

    const _handleContinueButtonPress = () => {

    };

    const _handleEndEditing = () => {
        if (!emailValue.match(/.+\@.+\..+/)) {
            Alert.alert(
                'Invalid Email',
                `Hmmm... You entered '${emailValue}' and something doesn't look quite right...`,
            );

            return;
        }

        getEmailAvailability(emailValue)
            .then((result) => {
                const { available } = result;

                console.log(`EmailInput._validateEmail => getEmailAvailability(${emailValue}):`, result);

                if (available) {
                    handleValidEmailEntry(emailValue);
                }

                setEmailAvailable(available);
            });
    };

    return (
        <View style={[styles.sectionWrap, styles.password, isRequired && styles.requiredWrap]}>
            <TextInput
                autoCapitalize="none"
                keyboardType="email-address"
                onChangeText={setEmail}
                onEndEditing={showContinueButton ? null : _handleEndEditing}
                placeholder={STRINGS.PLACEHOLDER}
                style={[styles.textInput, isRequired && styles.requiredInput]}
                value={emailValue || ''}
            />
            {isEmailAvailable === false && (
                <View style={styles.emailTaken}>
                    <Text style={{color:'red'}}>{STRINGS.REGISTERED}</Text>
                    <Button title={STRINGS.RESET_PASSWORD} onPress={() => {}} />
                </View>
            )}
            {showContinueButton && !isEmailAvailable && (
                <Button
                    onPress={_handleEndEditing}
                    title={STRINGS.CONTINUE}
                />
            )}
        </View>
    );
}

EmailInput.propTypes = {
    email: PropTypes.string,
    handleValidEmailEntry: PropTypes.func.isRequired,
    isRequired: PropTypes.bool,
    showContinueButton: PropTypes.bool,
};

EmailInput.defaultProps = {
    email: null,
    isRequired: false,
    showContinueButton: false,
}
