import { useDynamicConfig } from '@statsig/react-bindings';
import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
import { twMerge } from 'tailwind-merge';

import Avatar, { AvatarMaskShape } from '@/components/image/Avatar';
import Link from '@/components/link/Link';
import ProfileLink from '@/components/link/ProfileLink';
import VerifiedBadge from '@/components/timbaland/VerifiedBadge';
import { FALLBACK_IMAGE_URL, SMALL_IMAGE } from '@/utils/constants';
import { isVerifiedProfile } from '@/utils/utils';

export type ArtistTagProps = {
  avatarClassName?: string;
  avatarWrapClassName?: string;
  displayName?: string | null;
  handle: string;
  imageUrl?: string;
  showAvatar?: boolean;
  fontSize?: number;
  isVerified?: boolean;
  personaId?: string;
  personaImageUrl?: string;
  personaDisplayName?: string;
  fallbackSrc?: string | false;
};

export type Props = ArtistTagProps &
  Omit<React.HTMLAttributes<HTMLDivElement>, keyof ArtistTagProps>;

const ArtistTag: React.FC<Props> = observer((props) => {
  const {
    className,
    avatarClassName,
    avatarWrapClassName,
    displayName,
    handle,
    imageUrl,
    showAvatar = true,
    fontSize,
    isVerified = isVerifiedProfile({ handle: handle || '' }),
    personaId,
    personaImageUrl,
    personaDisplayName,
    fallbackSrc = FALLBACK_IMAGE_URL,
    ...restProps
  } = props;

  const { value: verifiedProfiles } = useDynamicConfig('verified-profiles');
  const handles = (verifiedProfiles?.handles as string[]) || [];

  const isVerifiedArtistProfile =
    isVerified || isVerifiedProfile({ handle: handle || '' }, handles);

  const showPersona = !!personaId;
  const [showTooltip, setShowTooltip] = useState(false);

  const handleClick = useCallback(
    (e: React.MouseEvent<HTMLAnchorElement>) => e.stopPropagation(),
    []
  );

  return (
    <div
      className={twMerge(
        'flex w-fit flex-row items-center gap-2 font-sans text-sm font-medium text-foreground-primary',
        className
      )}
      {...restProps}
    >
      <div
        className={twMerge(
          clsx('relative h-8 shrink-0', {
            'aspect-square': !showPersona,
            'aspect-3/2': showPersona,
          }),
          avatarWrapClassName
        )}
      >
        {showPersona && (
          <Link
            className={twMerge(
              'absolute right-0 bottom-0 z-0 overflow-visible',
              'transition-all duration-200',
              'hover:z-20 hover:translate-y-[-2px] hover:scale-105',
              'aspect-square h-full',
              avatarClassName
            )}
            href={`/persona/${personaId}`}
            onClick={handleClick}
            onMouseEnter={() => setShowTooltip(true)}
            onMouseLeave={() => setShowTooltip(false)}
          >
            <Avatar
              imageSize={SMALL_IMAGE}
              className='h-full w-full object-cover'
              src={personaImageUrl || ''}
              alt='Persona image'
              maskShape={AvatarMaskShape.Persona}
              fallbackSrc={fallbackSrc}
            />
            {showTooltip && (
              <div className='absolute top-1/2 left-full z-30 ml-1 max-w-[90px] -translate-y-1/2 transform truncate rounded bg-background-secondary px-2 py-1 text-xs text-foreground-primary'>
                {personaDisplayName}
              </div>
            )}
          </Link>
        )}
        {showAvatar && (
          <ProfileLink
            className={twMerge(
              'relative z-10 block',
              'aspect-square h-full',
              avatarClassName
            )}
            handle={handle}
          >
            <Avatar
              className='h-full w-full object-cover p-1'
              src={imageUrl || null}
              imageSize={SMALL_IMAGE}
              alt='Profile avatar'
              fallbackSrc={fallbackSrc}
            />
            {isVerifiedArtistProfile && (
              <VerifiedBadge className='absolute end-0 bottom-0 h-4 w-4 drop-shadow-avatar-overlay' />
            )}
          </ProfileLink>
        )}
      </div>
      <ProfileLink
        handle={handle}
        className='line-clamp-1 max-w-fit break-all'
        title={displayName || `@${handle}`}
        style={{ fontSize: fontSize }}
      >
        {displayName || `@${handle}`}
      </ProfileLink>
    </div>
  );
});

export default ArtistTag;
