import { Avatar, Spin, Tooltip } from 'antd';
import _ from 'lodash';
import React, { useMemo } from 'react';

import { qiniuImageView } from '../../utils/utils';
import styles from './index.module.css';

type PropType = {
  name?: string;
  src?: string;
  size?: string | number;
  loading?: boolean;
  alt?: string;
  icon?: any;
  width?: number;
  className?: string;
  onClick?: (e: any) => void;
  online?: boolean;
  group?: boolean;
};

const calSize = (size: string | undefined | number, width: number | undefined) => {
  let sizeNumber = 32;
  if (typeof size === 'number') {
    sizeNumber = size;
  } else if (size !== 'auto') {
    switch (size) {
      case 'small':
        sizeNumber = 24;
        break;
      case 'large':
        sizeNumber = 40;
        break;
      default:
    }
  } else if (width) {
    sizeNumber = Math.floor(width * 0.8);
  }
  return sizeNumber;
};

const formatURL = (src: string | undefined, size: number) => {
  let formatedURL = src;
  if (src) {
    formatedURL = qiniuImageView(src, 5, size * 2);
  }
  return formatedURL;
};

const CustomizedAvatar: React.FC<PropType> = ({
  name,
  src,
  size,
  loading,
  alt,
  icon,
  width,
  online,
  group,
  ...props
}) => {
  const sizeNumber = useMemo(() => calSize(size, width), [size, width]);
  const formatedURL = src?.startsWith('http') ? formatURL(src, sizeNumber) : src;
  const getImageAvatar = () => {
    return (
      <Tooltip title={name ?? ''}>
        {group ? (
          <Avatar src={formatedURL} size={sizeNumber} icon={icon} alt={alt} {...props} />
        ) : (
          <span className="relative">
            <Avatar src={formatedURL} size={sizeNumber} icon={icon} alt={alt} {...props} />
            {loading && (
              <div className="absolute" style={{ top: 0, left: 0, right: 0 }}>
                <Spin />
              </div>
            )}
            <div className={online ? styles.avatarOnline : ''} />
          </span>
        )}
      </Tooltip>
    );
  };

  const getColorTextAvatar = (color: string, text: string, otherProps?: any) => (
    <Avatar style={{ backgroundColor: color }} size={sizeNumber} alt={alt} {...props}>
      <div
        style={{
          fontSize: sizeNumber / 2,
          fontWeight: 'bold',
          textTransform: 'uppercase',
          ...otherProps,
        }}
      >
        {text}
      </div>
    </Avatar>
  );

  const getColorAvatar = (color: string, text: string) => {
    return (
      <Tooltip title={name ?? ''}>
        {group ? (
          getColorTextAvatar(color, text, size === 'auto' ? {} : { 'line-height': sizeNumber - 2 })
        ) : (
          <div className="relative">
            {getColorTextAvatar(color, text)}
            <div className={online ? styles.avatarOnline : ''} />
          </div>
        )}
      </Tooltip>
    );
  };

  const split = (s: string | undefined) => _.filter(s?.split(/(#)(?!.*\1)/), (l: string) => l !== '#');

  const getAvatarView = () => {
    if (size === 'auto') {
      if (formatedURL?.startsWith('http') || !formatedURL) {
        return group ? getImageAvatar() : <div className="w-full">{getImageAvatar()}</div>;
      }
      const data = split(formatedURL);
      if (data && data.length === 2) {
        return group ? (
          getColorAvatar(data[0], ` ${data[1]} `)
        ) : (
          <div className="w-full">{getColorAvatar(data[0], ` ${data[1]} `)}</div>
        );
      }
      return (
        // eslint-disable-next-line react/jsx-no-useless-fragment
        <>
          {group ? (
            <Avatar size={sizeNumber} />
          ) : (
            <div className="relative">
              <Avatar size={sizeNumber} />
              <div className={online ? styles.avatarOnline : ''} />
            </div>
          )}
        </>
      );
    }
    if (formatedURL?.startsWith('http') || !formatedURL) {
      return getImageAvatar();
    }
    const data = split(formatedURL);
    if (data && data.length === 2) {
      return getColorAvatar(data[0], data[1]);
    }
    return (
      // eslint-disable-next-line react/jsx-no-useless-fragment
      <>
        {group ? (
          <Avatar size={sizeNumber} icon={icon} />
        ) : (
          <div className="relative">
            <Avatar size={sizeNumber} icon={icon} />
            <div className={online ? styles.avatarOnline : ''} />
          </div>
        )}
      </>
    );
  };

  return getAvatarView();
};

export default CustomizedAvatar;
