import { forwardRef } from "react";

/**
 * FormControl
 *
 * column:         boolean - two-column layout (label left, input right)
 * label:          string | ReactNode - label text
 * htmlFor:        string - ties the label to its input id
 * labelAlt:       string | ReactNode - supplementary label (right side or sub-text in column mode)
 * error:          string | ReactNode - validation message; shown via CSS on invalid state
 * altBottom:      string | ReactNode - bottom-left supplementary text
 * altBottomRight: string | ReactNode - bottom-right supplementary text
 */
const FormControl = forwardRef(function FormControl(
  {
    column = false,
    label,
    htmlFor,
    labelAlt,
    error,
    altBottom,
    altBottomRight,
    className = "",
    children,
    ...props
  },
  ref
) {
  const wrapperClass = column ? "prs-form-control-col" : "prs-form-control";

  return (
    <div ref={ref} className={[wrapperClass, className].filter(Boolean).join(" ")} {...props}>
      {(label || labelAlt) && (
        <div className={`prs-label${column ? " prs-label-col" : ""}`}>
          {label && (
            <label htmlFor={htmlFor} className="prs-label-text">
              {label}
            </label>
          )}
          {labelAlt && (
            <span className={`prs-label-text${column ? " prs-label-text-sub" : ""}`}>
              {labelAlt}
            </span>
          )}
        </div>
      )}

      <div className="prs-form-control">
        {children}

        {(error || altBottom || altBottomRight) && (
          <div className="prs-label">
            {error && <span className="prs-label-text prs-label-error">{error}</span>}
            {altBottom && <span className="prs-label-text">{altBottom}</span>}
            {altBottomRight && <span className="prs-label-text">{altBottomRight}</span>}
          </div>
        )}
      </div>
    </div>
  );
});

export default FormControl;
