import { ConfigProvider, TransferProps, Transfer as OldTransfer } from 'antd';
import { TransferItem } from 'antd/es/transfer';
import { Icon } from '../Icon';
import React, { useContext, useEffect, useState, useCallback } from 'react';
import './index.less';
import classNames from 'classnames';
import { translate } from '../utils';

interface ExtraProps {
  type?: 'simple';
}

// TODO 类型报错
const Transfer: React.FC<TransferProps<TransferItem> & ExtraProps> = (
  props,
) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-transfer');
  const { titles = [,], oneWay: oneWayProps, targetKeys, type } = props;
  const oneWay = oneWayProps || type === 'simple';
  const [newTargetKeys, setTargetKeys] = useState(targetKeys);
  useEffect(() => {
    setTargetKeys(targetKeys);
  }, [targetKeys]);

  const getTitles = useCallback(() => {
    return titles.map((title, index) => {
      if (index === 1 && oneWay) {
        return (
          <span className={classNames(`${prefixCls}-title`)}>
            <span className={classNames(`${prefixCls}-text`)}>{title}</span>
            <span
              onClick={() => {
                setTargetKeys([]);
                props.onChange && props.onChange([], 'right', targetKeys);
              }}
              className={classNames(`${prefixCls}-title-delete`)}
            >
              <Icon iconName="Delete"></Icon>
            </span>
          </span>
        );
      }

      return title;
    });
  }, [titles]);

  const { locale } = useContext(ConfigProvider.ConfigContext);

  return (
    <OldTransfer
      locale={{
        itemUnit: '',
        itemsUnit: '',
        searchPlaceholder: translate(
          'packages.base.src.Transfer.index.请输入搜索内容',
          locale?.locale,
        ),
      }}
      oneWay={oneWay}
      {...props}
      titles={getTitles()}
      targetKeys={newTargetKeys}
      className={classNames(`${prefixCls}`, props.className, {
        [`${prefixCls}-oneWay`]: oneWay,
        [`${prefixCls}-simple`]: type === 'simple',
      })}
    ></OldTransfer>
  );
};

export { Transfer };
