import React from 'react';
import { Input, Tooltip } from 'antd';

export interface NameEditProp {
  initValue: string | null;
  disabledEdit?: boolean;
  onChange?: (value: string) => void;
}

const NameEdit: React.FC<NameEditProp> = function ({ initValue, disabledEdit = false, onChange }) {
  const [editing, setEditing] = React.useState<boolean>(false);
  const [value, setValue] = React.useState<string>('');

  React.useEffect(() => {
    setValue(initValue || '');
  }, [initValue]);

  return (
    <div
      className="hover:text-primary w-full h-full flex items-center cursor-pointer"
      onClick={() => {
        !disabledEdit && setEditing(true);
      }}
      onBlur={() => {
        setEditing(false);
        onChange?.(value);
      }}>
      {editing ? (
        <Input
          autoFocus
          maxLength={16}
          value={value}
          onChange={(e) => setValue(e.currentTarget.value)}
          onPressEnter={() => {
            setEditing(false);
            onChange?.(value);
          }}
        />
      ) : (
        <Tooltip title={value} placement="bottom">
          <span className="truncate">{value || '未命名'}</span>
        </Tooltip>
      )}
    </div>
  );
};

export default NameEdit;
