import { Input } from '@easyv/antd';
import message from 'components/message';
import { getThemesConfig } from 'models/theme';
import { ThemeType } from 'models/theme.types';
import React, { useCallback, useState } from 'react';
import { useDispatch } from 'react-redux';
import { updateThemeById } from 'services/theme';
import { Type } from 'models/theme.types';
import classNames from 'classnames';
import styles from './index.less';

type Props = {
  themeConfig: ThemeType;
  className?: string;
};

const EditeThemeName = (props: Props) => {
  const { className, themeConfig } = props;
  const dispatch = useDispatch();
  const [isEdite, setIsEdite] = useState(false);
  const updateThemeConfig = useCallback(
    async (data) => {
      const res = await updateThemeById(data);
      if (res) {
        message.success('重命名成功');
        dispatch(getThemesConfig());
      }
    },
    [themeConfig],
  );

  return isEdite ? (
    <Input
      autoFocus
      className={styles.input}
      placeholder="请输入新的名字"
      defaultValue={themeConfig.name}
      onBlur={(e) => {
        setIsEdite(!isEdite);
        if (e.target.value === themeConfig.name || !e.target.value.trim()) return;
        updateThemeConfig({ ...themeConfig, name: e.target.value });
      }}
      onPressEnter={(e: any) => e.target.blur()}
    />
  ) : (
    <span
      onDoubleClick={() => {
        // 系统主题名称不可以编辑
        themeConfig.type !== Type.SYSTEM && setIsEdite(!isEdite);
      }}
      className={classNames(themeConfig.type === Type.USER ? styles.userName : '', className)}>
      {themeConfig.name}
    </span>
  );
};

export default EditeThemeName;
