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

import { PERSONA_SHAPE_IMAGE } from '@/app/(root)/persona/[slug]/constants';
import { SkeletonBone } from '@/components/layout/Skeleton';

import ImageWithFallback, {
  Props as ImageWithFallbackProps,
} from './ImageWithFallback';

export type Props = Omit<ImageWithFallbackProps, 'alt' | 'fallbackSrc'> & {
  alt?: string;
  displayName?: string;
  handle?: string;
  size?: ImageWithFallbackProps['width'];
  maskShape?: Pick<
    React.CSSProperties,
    | 'mask'
    | 'WebkitMask'
    | 'maskSize'
    | 'WebkitMaskSize'
    | 'maskRepeat'
    | 'WebkitMaskRepeat'
    | 'maskPosition'
    | 'WebkitMaskPosition'
  >;
  fallbackSrc?: string | false;
} & ({ alt: string } | { displayName: string } | { handle: string });

/**
 * Mask shapes are applied via CSS properties
 */
export const AvatarMaskShape = {
  Persona: {
    mask: `url(${PERSONA_SHAPE_IMAGE})`,
    WebkitMask: `url(${PERSONA_SHAPE_IMAGE})`,
    maskSize: 'contain',
    WebkitMaskSize: 'contain',
    maskRepeat: 'no-repeat',
    WebkitMaskRepeat: 'no-repeat',
    maskPosition: 'center',
    WebkitMaskPosition: 'center',
  } satisfies Props['maskShape'],
};

const Avatar: React.FC<Props> = (props) => {
  const {
    displayName,
    handle,
    size,
    maskShape,
    src,
    fallbackSrc = false,
    ...restProps
  } = props;

  const className = maskShape
    ? props.className
    : twMerge('rounded-full', props.className);
  const style =
    props.style && maskShape
      ? { ...props.style, ...maskShape }
      : props.style || maskShape;

  return fallbackSrc === false && !src ? (
    <SkeletonBone className={className} style={style} />
  ) : (
    <ImageWithFallback
      alt={displayName || `@${handle}`}
      width={size}
      height={size}
      src={src}
      fallbackSrc={fallbackSrc || undefined}
      {...restProps}
      className={className}
      style={style}
    />
  );
};

export default Avatar;
