import { useState, useEffect } from 'react'
import { head, pathOr } from 'ramda';

// store
import { useStoreValue } from '../../../../store';
import renderHtmlContent from '../../../../helpers/renderHtmlContent';

const BuilderElementProperLabel = ({ id, defaultLabel }) => {
    const elements = useStoreValue('formElements');
    const element = head(elements.filter(o => o.id === id));
    const [label, setLabel] = useState('');
    const isRequired = pathOr(false, ['validators', 'isRequired'], element);
    const customValidation = pathOr(false, ['validators', 'custom'], element);
    let maybeNonEmptyTables = customValidation === 'nonEmptyTables';

    useEffect(() => {
        const label = head(element.settings.filter(o => o.name === 'label'));
        const text = head(element.settings.filter(o => o.name === 'text'));

        if (label) {
            setLabel(label.value);
        } else if (text) {
            setLabel(text.value);
        } else {
            setLabel(defaultLabel);
        }
    }, [elements]);

    return <div className="label">
        {renderHtmlContent(label)}
        {isRequired || maybeNonEmptyTables ? <span className="appForm__field--required">*</span> : null}
    </div>
}

export default BuilderElementProperLabel;