import cx from "classnames";
import React from "react";

const CLASS_ROOT = "textarea";

export type TextAreaSize = "default" | "large";
export type TextAreaWidth = "default" | "fullwidth";

export interface TextAreaProps
  extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  /** Html id attribute. */
  id: string;
  /** Disabled state. */
  isDisabled?: boolean;
  /** Invalid state */
  isInvalid?: boolean;
  /** Readonly state. */
  isReadonly?: boolean;
  /** Valid state */
  isValid?: boolean;
  /** Html name attribute. If not present, id is used.*/
  name?: string;
  /** Placeholder text */
  placeholder?: string;
  /** Size of element. */
  size?: TextAreaSize;
  /** Input width */
  width?: TextAreaWidth;
  /** Additional CSS classes */
  className?: string;
  /** Child elements */
  children?: React.ReactNode;
}

const defaultProps = {
  size: "default" as TextAreaSize,
  width: "default" as TextAreaWidth,
};

const TextArea: React.FC<TextAreaProps> = ({
  children,
  className,
  id,
  isDisabled,
  isInvalid,
  isValid,
  isReadonly,
  placeholder,
  size = defaultProps.size,
  width = defaultProps.width,
  name,
  ...other
}) => {
  const classes = cx(
    CLASS_ROOT,
    {
      "is-invalid": isInvalid,
      "is-valid": isValid,
      [`${CLASS_ROOT}--${size}`]: size !== defaultProps.size,
      [`${CLASS_ROOT}--${width}`]: width !== defaultProps.width,
    },
    className,
  );

  const elementName = name || id;

  return (
    <textarea
      className={classes}
      id={id}
      name={elementName}
      disabled={isDisabled}
      readOnly={isReadonly}
      placeholder={placeholder}
      {...other}
    >
      {children}
    </textarea>
  );
};

TextArea.displayName = "TextArea";

export { TextArea };
