import { Tag as OldTag, TagProps, ConfigProvider } from 'antd';
import React, { useCallback, useContext, useMemo, useState } from 'react';
import './index.less';
import classNames from 'classnames';
import { AOP } from '../utils/AOP';
import { Input } from '../Input';
import { translate } from '../utils';

interface TagExtraProps {
  type?: 'warning' | 'primary' | 'error' | 'success' | 'default';
  size?: 'large' | 'small' | 'middle';
  border?: boolean; // 是否有边框
  select?: boolean;
  isSelected?: boolean;
  disabled?: boolean;
  maxWidth?: string;
  isEdit?: boolean;
  onInput?: (v: any) => void;
  inputProps?: any;
}

const Tag = ({
  size = 'middle',
  select = false,
  isSelected = false,
  disabled = false,
  maxWidth = '',
  type = 'default',
  isEdit = false,
  border = true,
  onInput,
  className,
  inputProps = {},
  ...props
}: TagProps & TagExtraProps) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-tag');

  const [showInput, setShowInput] = useState(false);
  const [selected, setSelected] = useState(isSelected);
  const newOnClick = new AOP<React.MouseEvent<HTMLSpanElement>, void>(
    props.onClick,
  )
    .before(() => {
      if (isEdit) setShowInput(true);
      if (select) setSelected((v) => !v);
    })
    .getFunction();

  const _pressEnter = (e: any) => {
    if (onInput) onInput(e.target.value);
    setShowInput(false);
  };
  const { locale } = useContext(ConfigProvider.ConfigContext);

  return (
    <div className={classNames(`${prefixCls}`, className)}>
      {isEdit && showInput ? (
        <Input
          size="small"
          placeholder={translate(
            'packages.base.src.Tag.index.请输入',
            locale?.locale,
          )}
          onPressEnter={_pressEnter}
          {...inputProps}
        />
      ) : (
        <OldTag
          {...props}
          onClick={newOnClick}
          className={classNames(
            `${prefixCls}-box`,
            `${prefixCls}-raduis`,
            `${prefixCls}--${size}`,
            {
              [`${prefixCls}--selected`]: selected,
              [`${prefixCls}--cursor`]: select,
              [`${prefixCls}--disabled`]: disabled,
              [`${prefixCls}--${type}`]: !props.color,
              [`${prefixCls}--no-border`]: !border,
            },
          )}
        >
          <span
            className={maxWidth && `${prefixCls}-text`}
            style={{ maxWidth }}
          >
            {props.children}
          </span>
        </OldTag>
      )}
    </div>
  );
};

export { Tag };
