'use client';

import type { ComponentProps } from 'react';
import * as AvatarPrimitive from '@radix-ui/react-avatar';
import { User } from 'lucide-react';

import { cn } from '@spoon/ui';

type BasedAvatarProps = ComponentProps<typeof AvatarPrimitive.Root> & {
  src?: string | null;
  fullName?: string | null;
  imageProps?: Omit<ComponentProps<typeof AvatarPrimitive.Image>, 'data-slot'>;
  fallbackProps?: ComponentProps<typeof AvatarPrimitive.Fallback>;
  userIconProps?: ComponentProps<typeof User>;
};

const BasedAvatar = ({
  src = null,
  fullName = null,
  imageProps,
  fallbackProps,
  userIconProps = {
    size: 32,
  },
  className,
  ...props
}: BasedAvatarProps) => {
  return (
    <AvatarPrimitive.Root
      data-slot='avatar'
      className={cn(
        'relative flex size-8 shrink-0 cursor-pointer overflow-hidden rounded-full',
        className,
      )}
      {...props}
    >
      {src ? (
        <AvatarPrimitive.Image
          {...imageProps}
          src={src}
          className={imageProps?.className}
        />
      ) : (
        <AvatarPrimitive.Fallback
          {...fallbackProps}
          data-slot='avatar-fallback'
          className={cn(
            'bg-muted flex size-full items-center justify-center rounded-full',
            fallbackProps?.className,
          )}
        >
          {fullName ? (
            fullName
              .split(' ')
              .map((n) => n[0])
              .join('')
              .toUpperCase()
          ) : (
            <User
              {...userIconProps}
              className={cn('', userIconProps.className)}
            />
          )}
        </AvatarPrimitive.Fallback>
      )}
    </AvatarPrimitive.Root>
  );
};

export { BasedAvatar };
