import React, { LegacyRef } from 'react';
import classNames from 'classnames';
import { InjectedFieldProps } from '../Field/InjectedFieldProps';
import { FormDefaults } from '../FormDefaults';
import Group, { GroupProps } from '../Group';

export interface TextAreaGroupProps
  extends InjectedFieldProps<string | undefined | null>,
    Omit<
      React.HTMLProps<HTMLTextAreaElement>,
      keyof InjectedFieldProps<any> | 'children' | 'className' | 'label'
    >,
    Omit<GroupProps, keyof InjectedFieldProps<any> | 'children'> {
  icon?: React.ReactNode;
}

function TextAreaGroup(
  {
    input,
    meta,
    label,
    helpText,
    className,
    required,
    disabled,
    icon,
    ...rest
  }: TextAreaGroupProps,
  ref: LegacyRef<HTMLTextAreaElement>
) {
  return (
    <Group
      input={input}
      meta={meta}
      required={required}
      disabled={disabled}
      label={label}
      helpText={helpText}
      className={classNames(
        className,
        FormDefaults.cssClassPrefix + 'text-area-group'
      )}>
      {icon}
      <textarea
        {...input}
        {...rest}
        value={input.value ?? ''}
        onChange={(val) => input.onChange(val.target.value)}
        ref={ref}
        className={classNames(
          className,
          FormDefaults.cssClassPrefix + 'text-area-group'
        )}
      />
    </Group>
  );
}

/** Generic controlled `<textarea/>` wrapped by a `<Group/>` */
const TextAreaGroupWithRef = React.forwardRef(
  TextAreaGroup
) as React.ComponentType<TextAreaGroupProps>;

export default TextAreaGroupWithRef;
