import React, { memo, Fragment, useState, useEffect, useRef } from 'react';
import { Input } from '@easyv/antd';
import styles from './EditableText.less';
import { EditSquareOutlined } from '@easyv/react-icons';

function EditableText({ text, onOk, children }) {
  const [editable, setEditable] = useState(false);
  const [name, setName] = useState(text);
  const inputRef = useRef<Input>(null);

  useEffect(() => {
    if (editable) {
      inputRef.current?.focus();
    }
  }, [editable]);
  const handleChange = (e) => {
    const value = e.target.value.trim();
    if (value.length < 12) {
      setName(value);
    }
  };

  const handleBlur = () => {
    if (name && name !== text) {
      onOk(name);
    } else {
      setName(text);
    }
    setEditable(false);
  };

  const handleClick = () => {
    setEditable(true);
  };

  return editable ? (
    <Input
      ref={inputRef}
      value={name}
      placeholder="请输入素材分类名称，12个字符以内"
      onChange={handleChange}
      onBlur={handleBlur}
      onPressEnter={(e: any) => e.target.blur()}
    />
  ) : (
    <Fragment>
      <span className={styles.name}>
        {name}
        {children}
      </span>
      <span className="iconsBox" onClick={handleClick}>
        <EditSquareOutlined className="categoryIcon" />
      </span>
    </Fragment>
  );
}

export default memo(EditableText);
