/**
 * Linted Form Field Component
 *
 * Wrapper component that adds lint validation to form fields.
 *
 * @package
 * @since   0.1.0
 */

import { cloneElement } from '@wordpress/element';
import SettingsLintMessage from '../SettingsLintMessage';
import './linted-form-field.css';

/**
 * Linted Form Field component
 *
 * @param {Object     } props           Component props.
 * @param {string     } props.fieldName Field name for validation.
 * @param {Object     } props.lintHook  Settings lint hook instance.
 * @param {JSX.Element} props.children  Form control component.
 * @param {string     } props.className Additional CSS class.
 * @return {JSX.Element}                Wrapped form field.
 */
const LintedFormField = ({ fieldName, lintHook, children, className = '' }) => {
  if (lintHook === null || !fieldName) {
    return children;
  }

  const { getFieldMessages, hasErrors, hasWarnings } = lintHook;
  const messages = getFieldMessages(fieldName);

  // Determine field status class
  let statusClass = '';
  if (hasErrors(fieldName) === true) {
    statusClass = 'prorank-field-has-error';
  } else if (hasWarnings(fieldName) === true) {
    statusClass = 'prorank-field-has-warning';
  }

  // Clone child element and add aria-describedby if there are messages
  const ariaDescribedBy =
    Array.isArray(messages) && messages.length > 0 ? `${fieldName}-lint-messages` : undefined;
  
  // Check if children exists before cloning
  const enhancedChild = children ? cloneElement(children, {
    'aria-describedby': ariaDescribedBy,
    'aria-invalid': hasErrors(fieldName) === true ? 'true' : undefined,
  }) : null;

  return (
    <div className={`prorank-linted-field ${statusClass} ${className}`}>
      {enhancedChild}
      {Array.isArray(messages) && messages.length > 0 && (
        <div id={`${fieldName}-lint-messages`} role="status">
          <SettingsLintMessage messages={messages} fieldName={fieldName} inline={true} />
        </div>
      )}
    </div>
  );
};

export default LintedFormField;
