/* eslint-disable react-hooks/exhaustive-deps */
import React, { memo, useState, useEffect, useRef, MouseEvent, ChangeEvent } from 'react';
import classnames from 'classnames';
import { Input } from '@easyv/react-gui';
import styles from './EditableText.less';

function EditableText({
  id,
  text,
  selected,
  focus,
  updateName
}: {
  id: number | string;
  text: string;
  selected: boolean;
  focus?: boolean;
  updateName: (name: string) => void;
}) {
  const inputEle = useRef<HTMLInputElement>(null);
  const [name, setName] = useState(text);
  const [editable, setEditable] = useState(false);

  useEffect(() => {
    setName(text);
  }, [text]);

  useEffect(() => {
    const handleRename = (e) => {
      if (e.value === id) {
        setEditable(true);
      }
    };

    window.addEventListener('rename', handleRename);
    return () => {
      window.removeEventListener('rename', handleRename);
    };
  }, [id]);

  useEffect(() => {
    if (editable) {
      inputEle.current?.focus();
      inputEle.current?.select();
    }
  }, [editable]);

  useEffect(() => {
    if (!selected) {
      setEditable(false);
    }
  }, [selected]);

  const onBlur = () => {
    if (name !== text) {
      if (name !== '') {
        updateName(name);
      } else {
        setName(text);
      }
    }
    setEditable(false);
  };

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

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setName(e.target.value);
  };

  return (
    <div className={classnames(styles.title, { [styles['title--focus']]: !selected && focus })}>
      {editable ? (
        <Input
          ref={inputEle}
          value={name}
          onChange={handleChange}
          placeholder="请输入图层名称"
          onPressEnter={(e: React.FocusEvent<HTMLInputElement>) => e.target.blur()}
          onBlur={onBlur}
          style={{ height: 23, background: '#24262E' }}
          draggable={true}
          onDragStart={(e: MouseEvent) => e.preventDefault()} // 防止框选文字的时候产生拖拽行为
        />
      ) : (
        <p className={styles.name} title={name} onDoubleClick={onDoubleClick}>
          {name}
        </p>
      )}
    </div>
  );
}

export default memo(EditableText);
