import { Avatar as OldAvatar, AvatarProps, ConfigProvider } from 'antd';
import React, { useContext, useMemo } from 'react';
import './index.less';
import classNames from 'classnames';
import { GroupProps } from 'antd/lib/avatar';
import man from './icons/man.png';
import woman from './icons/woman.png';
import aydin from './icons/aydin.png';

interface AvatarExtraProps {
  type?: 'woman' | 'man' | 'aydin';
}

const Sizes = {
  large: 40,
  default: 32,
  small: 24,
};

const Avatar = (props: AvatarProps & AvatarExtraProps) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-avatar');

  const { size = 'default', style, type } = props;

  const _style = useMemo(
    () => ({
      backgroundColor: 'var(--primary-6)',
      ...style,
    }),
    [style],
  );
  const types = { man, woman, aydin };

  return (
    <OldAvatar
      src={types[type] || null}
      {...props}
      className={classNames(`${prefixCls}-box`, props.className)}
      size={Sizes[size as any] || size}
      style={_style}
    >
      {props.children}
    </OldAvatar>
  );
};

interface AvatarGroupExtraProps {
  maxText?: string | number;
}

const Group: React.FC<GroupProps & AvatarGroupExtraProps> = props => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-avatar-group');

  const { size = 'default', maxCount, maxText } = props;
  const _moreText = useMemo(() => {
    if (!maxCount) {
      return null;
    }
    // @ts-ignore
    const length = props.children?.length;
    if (!maxText) {
      return length ? `+${length - maxCount}` : null;
    }
    return maxText;
  }, [maxCount, props.children, maxText]);

  return (
    <div className={classNames(`${prefixCls}-outer-box`)}>
      <OldAvatar.Group
        {...props}
        maxStyle={{
          background: 'transparent',
          fontSize: '16px',
          color: 'transparent',
          zIndex: 2,
          border: 'none',
        }}
        className={classNames(`${prefixCls}-box`, props.className)}
        size={Sizes[size as any] || size}
      >
        {/* @ts-ignore */}
        {props.children?.map(item => ({
          ...item,
          props: { size: Sizes[size as any] || size, ...item.props },
        }))}
      </OldAvatar.Group>
      {_moreText && (
        <div
          className={classNames(`${prefixCls}-more-box`)}
          style={{
            width: `${Sizes[size as any] || size}px`,
            lineHeight: `${Sizes[size as any] || size}px`,
            fontSize: `${(Sizes[size as any] || size) - 24}px`,
            ...props.maxStyle,
          }}
        >
          {_moreText}
        </div>
      )}
    </div>
  );
};

Avatar.Group = Group;

export { Avatar };
