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

import { getNomAvailaibility } from '../../../api/profile.js';
import styles from '../Profile.styles.js';

const STRINGS = {
    ABOUT_GENERATED_NOM:
        'You currently have a generated Nom De Bid - the alias other bidders will know you as - why not personalize it?',
    CHECK_AVAILABILITY: 'check availability',
    NOM_EXPLANATION:
        "Selecting a nom de bid allows you to bid anonymously - or not. By default, we'll use your first initial and last name.",
    ONLY_SET_ONCE: 'This can only be set once!',
    PLACEHOLDER: 'nom de bid',
    SUBMIT_NOM: 'Set Nom De Bid',
};

export default function EditNomDeBid({
    isGeneratedNomDeBid,
    isStandalone,
    nomDeBid,
    updateNomDeBid,
}) {
    const [newNom, setNomDeBid] = useState(isGeneratedNomDeBid || !nomDeBid ? '' : nomDeBid);
    const [isNomValid, setValidNom] = useState(null);

    const _handleEndEditing = (updateOnValid = false) => () => {
        getNomAvailaibility(newNom).then((result) => {
            setValidNom(result.available);

            if (updateOnValid && result.available) {
                updateNomDeBid(newNom);
            }
        });
    };

    const explanationString = isGeneratedNomDeBid
        ? `${STRINGS.ABOUT_GENERATED_NOM} ${STRINGS.ONLY_SET_ONCE}`
        : `${STRINGS.NOM_EXPLANATION} ${STRINGS.ONLY_SET_ONCE}`;

    return (
        <View style={styles.profileFormWrap}>
            <Text style={styles.hintText}>{explanationString}</Text>
            <TextInput
                autoCapitalize="none"
                onChangeText={(text) => setNomDeBid(text)}
                onEndEditing={!isStandalone && _handleEndEditing(false)}
                placeholder={STRINGS.PLACEHOLDER}
                style={[styles.textInput, styles.requiredInput]}
                value={newNom}
            />
            {isNomValid === false && (
                <Text style={{color:'red'}}>Nom De Bid is taken!</Text>
            )}
            {isNomValid === true && (
                <Text style={{color:'green'}}>Nom De Bid is available!</Text>
            )}
            <Button
                title={isStandalone ? STRINGS.CHECK_AVAILABILITY : STRINGS.SUBMIT_NOM}
                onPress={_handleEndEditing(true)}
            />
        </View>
    );
}

EditNomDeBid.propTypes = {
    isGeneratedNomDeBid: PropTypes.bool,
    isStandalone: PropTypes.bool,
    nomDeBid: PropTypes.string,
    updateNomDeBid: PropTypes.func.isRequired,
};

EditNomDeBid.defaultProps = {
    isGeneratedNomDeBid: false,
    isStandalone: false,
    nomDeBid: null,
};
