import { React, PropTypes, classnames } from '@gravityforms/libraries';
import { useIdContext, useStoreContext } from '@gravityforms/react-utils';
import HelpText from '../../elements/HelpText';
import { getId } from './utils';

const { forwardRef } = React;

/**
 * @module DropdownLabel
 * @description The label for the dropdown.
 *
 * @since 4.5.0
 *
 * @param {object}              props                 Component props.
 * @param {string}              props.label           The label for the dropdown.
 * @param {object}              props.labelAttributes Custom attributes for the label.
 * @param {string|Array|object} props.labelClasses    Custom classes for the label.
 * @param {object}              ref                   Ref to the component.
 *
 * @return {JSX.Element} The label component.
 */
const DropdownLabel = forwardRef( ( {
	label = '',
	labelAttributes = {},
	labelClasses = [],
	required = false,
	requiredLabel = {
		size: 'text-sm',
		weight: 'medium',
	},
}, ref ) => {
	const id = useIdContext();
	const triggerRef = useStoreContext( ( state ) => state.triggerRef );

	if ( ! label ) {
		return null;
	}

	const labelId = getId( id, 'label' );
	const helpTextId = getId( id, 'help-text' );

	const labelProps = {
		className: classnames( [
			'gform-dropdown__label',
			'gform-text',
			'gform-text--color-port',
			'gform-typography--size-text-sm',
			'gform-typography--weight-medium',
		], labelClasses ),
		...labelAttributes,
		id: labelId,
		onClick: () => triggerRef?.current?.focus(),
	};

	const requiredLabelProps = {
		customClasses: classnames(
			[ 'gform-input-help-text--required', 'gform-input-help-text--required-dropdown' ],
		),
		id: helpTextId,
		...requiredLabel,
	};

	return <div { ...labelProps } ref={ ref }>{ label }{ required && <HelpText { ...requiredLabelProps } /> }</div>;
} );

DropdownLabel.propTypes = {
	label: PropTypes.string,
	labelAttributes: PropTypes.object,
	labelClasses: PropTypes.oneOfType( [
		PropTypes.string,
		PropTypes.array,
		PropTypes.object,
	] ),
};

export default DropdownLabel;
