import { clsx } from 'clsx';
import { useMemo } from 'react';

import { getBrandColorFromSeed, Theme } from '../common';

import Circle from '../common/circle';

type NumericAvatarSize = 24 | 40 | 48 | 56 | 72;

type LegacyAvatarSize = 'sm' | 'md' | 'lg';

export type AvatarSize = NumericAvatarSize | LegacyAvatarSize;

export type AvatarTheme = 'light' | 'dark';

export type AvatarType = 'thumbnail' | 'icon' | 'emoji' | 'initials';

/**
 * @deprecated `Avatar` is deprecated please use `AvatarView` instead
 */
export interface AvatarProps {
  backgroundColor?: string;
  backgroundColorSeed?: string;
  children?: React.ReactNode;
  className?: string;
  outlined?: boolean;
  size?: AvatarSize;
  theme?: AvatarTheme;
  type?: AvatarType;
  'aria-label'?: string;
}

const backwardsCompatibleSize = (size: AvatarSize): NumericAvatarSize => {
  switch (size) {
    case 'sm':
      return 24;

    case 'md':
      return 48;

    case 'lg':
      return 72;

    default:
      return size;
  }
};

/**
 * @deprecated Use `AvatarView` component instead
 */
const Avatar: React.FC<AvatarProps> = ({
  backgroundColor = null,
  backgroundColorSeed = null,
  children = null,
  className,
  outlined = false,
  size: sizeFromProps = 48,
  theme = Theme.LIGHT,
  type = 'thumbnail',
  'aria-label': ariaLabel,
}) => {
  const backgroundColorFromSeed = useMemo<string | undefined>(
    () =>
      !backgroundColor && backgroundColorSeed
        ? getBrandColorFromSeed(backgroundColorSeed)
        : undefined,
    [backgroundColor, backgroundColorSeed],
  );

  const size = backwardsCompatibleSize(sizeFromProps);

  return (
    <div
      className={clsx('tw-avatar', className, `tw-avatar--${size}`, `tw-avatar--${type}`, {
        'tw-avatar--outlined': outlined,
        'tw-avatar--branded': Boolean(backgroundColorFromSeed),
        'np-text-title-body': type === 'initials',
      })}
      aria-label={ariaLabel}
    >
      <div
        className="tw-avatar__content"
        style={{
          backgroundColor: backgroundColor || backgroundColorFromSeed,
        }}
      >
        {children}
      </div>
    </div>
  );
};

export default Avatar;
