'use strict';

import React, { useEffect, useRef, useState } from 'react';

export default ({
    type = 'text',
    id = '',
    className = '',
    cur_value = '',
    placeholder = '',
    blurHandler = null,
    disabled = false
}) => {
    let el = useRef(null);
    
    const [ value, setValue ] = useState(cur_value);

    function handleChange(e){
        setValue(e.target.value);
    }

    useEffect(() => {
        el.current.addEventListener('blur', () => {
            if(blurHandler != null){
                blurHandler(value);
            }
        });
    });

    let attrs = {
        type,
    };
    if(id.length > 0){
        attrs.id = id;
    }
    if(className.length > 0){
        attrs.class = className;
    }
    if(placeholder.length > 0){
        attrs.placeholder = placeholder;
    }
    if(disabled){
        attrs.disabled = disabled;
    }
    return (
        <input
            ref={el}
            onChange={handleChange}
            value={value}
            { ...attrs }
        />
    )
}
