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

export default memo(function EditableText({
  id,
  text,
  selected,
  updateName
}: {
  id: string | number;
  text: string;
  selected: boolean;
  updateName: (name) => any;
}) {
  const inputEle = useRef<Input>(null);
  const valueRef = useRef<{ _text?: string; _name?: string }>({});
  const nameRef = useRef(null);
  const [value, setValue] = useState<{ text?: string; editable: boolean }>({ text, editable: false });

  useEffect(() => {
    setValue((preState) => ({ ...preState, text }));
    valueRef.current._text = text;
  }, [text]);

  useEffect(() => {
    if (value.editable) {
      inputEle.current?.focus();
      inputEle.current?.select();
    } else {
      const text = valueRef.current._text;
      const name = valueRef.current._name;
      if (text !== name) {
        if (name) {
          updateName({ id, name });
        } else {
          setValue({ text: text, editable: false });
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value.editable]);

  useEffect(() => {
    if (!selected) {
      setValue((preState) => ({ ...preState, editable: false }));
    }
  }, [selected]);

  const onBlur = () => {
    setValue((preState) => ({ ...preState, editable: false }));
  };

  const onDoubleClick = () => {
    setValue({ text: value.text, editable: true });
  };

  const handleChange = (e) => {
    setValue({ text: e.target.value, editable: true });
    valueRef.current._name = e.target.value;
  };

  return (
    <div className={styles.title} ref={nameRef}>
      {value.editable ? (
        <Input
          ref={inputEle}
          value={value.text}
          onChange={handleChange}
          placeholder="请输入状态名称"
          onPressEnter={(e: any) => e.target.blur()}
          onBlur={onBlur}
          style={{ height: 23, background: '#24262E' }}
        />
      ) : (
        <p className={styles.name} title={value.text} onDoubleClick={onDoubleClick}>
          {value.text}
        </p>
      )}
    </div>
  );
});
