import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { getLabelRequiredText } from '../../tools/components/formLabel';
import { REQUIRED_NOTATION } from '../../constants/strings';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/FormLabel.scss';

const n = createNamespace('FormLabel');

const FormLabel = ({
    labelText,
    required,
    labelProps,
    textProps,
    htmlFor,
    hiddenText,
    i18n,
    children
}) => {
    if (!labelText) {
        return null;
    }

    const {
        className: labelTextClass
    } = textProps;

    const {
        className: labelClass
    } = labelProps;

    const i18nWithDefaults = { ...FormLabel.defaultProps.i18n, ...i18n };

    return (
        <label {...n('label').withClass(labelClass).withTestId().withE2EId().props} htmlFor={htmlFor}>
            <span {...n('text', hiddenText && 'hidden').withClass(labelTextClass).withTestId().props}>
                {labelText}
            </span>
            {required && !hiddenText && (
                <>
                    <span aria-hidden="true" {...n('required').withTestId().props}>{REQUIRED_NOTATION}</span>
                    {i18nWithDefaults.fieldRequired && (
                        <span {...n('requiredText').withTestId().props}>{getLabelRequiredText(i18nWithDefaults.fieldRequired)}</span>
                    )}
                </>
            )}
            {children}
        </label>
    );
};

FormLabel.propTypes = {
    labelText: PropTypes.string.isRequired,
    labelProps: PropTypes.object,
    textProps: PropTypes.object,
    required: PropTypes.bool,
    htmlFor: PropTypes.string,
    hiddenText: PropTypes.bool,
    i18n: PropTypes.shape({
        fieldRequired: PropTypes.string
    })
};
FormLabel.defaultProps = {
    labelProps: {},
    textProps: {},
    required: false,
    htmlFor: null,
    hiddenText: false,
    i18n: {
        fieldRequired: ''
    }
};

export default FormLabel;
