import { useState, useRef, useEffect } from "react";

import "./Textarea.css";
import { getCN, randomId, usePadding, renderProps } from "../utils";

import FormField from "../../componentsDefault/FormField/FormField";

function Textarea({
  type = `text`,
  grow = true,
  before,
  after,
  status,
  onResize,
  top,
  value,
  hovered = `input`,
  bottom,
  rows = 1,
  maxHeight,
  onChange,
  ref = useRef(),
  ...props
}: {
  [x: string]: any;
}) {
  const [props_id, setPropsId] = useState(randomId(props.id, `textarea`));
  const [_value, _setValue] = useState(``);

  useEffect(() => {
    if (value && value.length >= 1) {
      _setValue(value);
    }
  }, [value]);

  useEffect(() => {
    const el = ref.current;

    if (grow && el?.offsetParent) {
      el.style.height = "";
      el.style.height = `${el.scrollHeight}px`;

      if (onResize) onResize(el.scrollHeight);
    }
  }, [grow, _value, onResize]);

  const _onChange = (e: any) => {
    _setValue(e.target.value);
    if (onChange) onChange(e);
  };

  return (
    <FormField
      onTouchStart={(e) => e.stopPropagation()}
      onTouchMove={(e) => e.stopPropagation()}
      onTouchEnd={(e) => e.stopPropagation()}

      before={before}
      after={after}
      status={status}
      top={top}
      bottom={bottom}
      {...props}
      hovered={hovered}
      className={getCN([
        `Textarea`,
        !before && after && "MYUI-FormField__in--after",
        before && !after && "MYUI-FormField__in--before",
        after && before && "MYUI-FormField__in--before_after",
      ])}
    >
      <textarea
        style={{ maxHeight }}
        rows={rows}
        aria-label={props_id}
        id={props_id}
        ref={ref}
        value={_value}
        onChange={_onChange}
        {...renderProps(props)}
      />
    </FormField>
  );
}

export default Textarea;
