import React, { useLayoutEffect, useRef } from "react";

const EditElement = (props) => {
  const {
    className,
    handleEditValue,
    value,
    setShowInputEle,
    showInputEle,
    handleFocus,
    handleBlur,
    i,
  } = props;
  const MIN_TEXTAREA_HEIGHT = 32;
  const textareaRef = useRef(null);

  useLayoutEffect(() => {
    // Reset height to shrink on delete
    textareaRef.current.style.height = "inherit";
    // Set height
    textareaRef.current.style.height = `${Math.max(
      textareaRef.current.scrollHeight,
      MIN_TEXTAREA_HEIGHT
    )}px`;
  }, [value]);

  return (
    <div>
      {showInputEle ? (
        <div
          style={{ width: "100%" }}
          onBlur={(e) => handleBlur(e, i)}
          tabIndex="0"
        ></div>
      ) : (
        <div
          style={{ width: "100%" }}
          onClick={() => handleFocus("plain-div onCLick, i", i)}
          onBlur={(e) => handleBlur(e, i)}
          className="outer-div"
          tabIndex="0"
        >
          <textarea
            ref={textareaRef}
            name={"text-box"}
            type="text"
            style={{
              minHeight: MIN_TEXTAREA_HEIGHT,
              resize: "none",
              color: "#4e4e4e",
              letterSpacing: ".02rem",
            }}
            value={value}
            className="edit-ele-input"
            onChange={(e) => handleEditValue(e, i)}
            autoFocus
          />
        </div>
      )}
    </div>
  );
};

export default EditElement;
