import { identity } from 'lodash-es';
import React from 'react';
import { twMerge } from 'tailwind-merge';

import Avatar from '@/components/image/Avatar';
import ProfileLink from '@/components/link/ProfileLink';
import { SMALL_IMAGE } from '@/utils/constants';

export type Props = React.HTMLAttributes<HTMLDivElement> &
  Pick<
    React.ComponentProps<typeof Avatar>,
    'displayName' | 'handle' | 'size' | 'maskShape' | 'imageSize' | 'alt'
  > & {
    avatarContainerClassName?: string;
    avatarClassName?: string;
    contentClassName?: string;
    imageUrl?: string;
    showAvatar?: boolean;
    alt?: string;
    href?: string;
    /**
     * Can be used to supply a function to decorate the avatar
     */
    avatar?: (baseAvatar: React.ReactNode) => React.ReactNode;
  };

const AvatarTag: React.FC<Props> = (props) => {
  const {
    children,
    className,
    avatarContainerClassName,
    avatarClassName,
    contentClassName,
    displayName,
    handle,
    href,
    alt,
    size,
    imageUrl,
    imageSize,
    maskShape,
    avatar: renderAvatar = identity<React.ReactNode>,
    ...restProps
  } = props;

  const profileLinkProps = href ? { href } : { handle: handle || '' };

  const avatar = renderAvatar(
    <ProfileLink
      className={twMerge('block h-8 w-8 rounded-full', avatarClassName)}
      {...profileLinkProps}
    >
      <Avatar
        className='h-full w-full object-cover'
        src={imageUrl || null}
        imageSize={SMALL_IMAGE}
        maskShape={maskShape}
        size={size}
        alt={alt}
        displayName={displayName}
        handle={handle || ''}
      />
    </ProfileLink>
  );

  return (
    <div
      className={twMerge('flex flex-row items-center gap-2', className)}
      {...restProps}
    >
      {avatar && (
        <div className={twMerge('relative shrink', avatarContainerClassName)}>
          {avatar}
        </div>
      )}
      <div className={twMerge('relative flex-1', contentClassName)}>
        {children || (
          <ProfileLink
            className='line-clamp-1 max-w-fit break-all'
            {...profileLinkProps}
          >
            {displayName || `@${handle}`}
          </ProfileLink>
        )}
      </div>
    </div>
  );
};

export default AvatarTag;
