'use client';

import { FC } from 'react';
import Image from 'next/image';
import { cn } from '@/utils/helpers';
import styles from './Avatar.module.scss';

export interface AvatarProps {
  src?: string;
  alt?: string;
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
  shape?: 'circle' | 'square';
  name?: string;
  online?: boolean;
  className?: string;
}

const sizeMap = {
  xs: 24,
  sm: 32,
  md: 40,
  lg: 48,
  xl: 64,
};

export const Avatar: FC<AvatarProps> = ({
  src,
  alt = 'avatar',
  size = 'md',
  shape = 'circle',
  name,
  online,
  className,
}) => {
  const getInitials = (name: string): string => {
    return name
      .split(' ')
      .map((n) => n[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  const pixelSize = sizeMap[size];

  return (
    <div
      className={cn(
        styles.avatar,
        styles[`avatar--${size}`],
        styles[`avatar--${shape}`],
        className
      )}
    >
      {src ? (
        <Image
          src={src}
          alt={alt}
          width={pixelSize}
          height={pixelSize}
          className={styles.avatar__image}
        />
      ) : name ? (
        <span className={styles.avatar__initials}>{getInitials(name)}</span>
      ) : (
        <span className={styles.avatar__placeholder}>
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
          </svg>
        </span>
      )}
      {online !== undefined && (
        <span
          className={cn(styles.avatar__status, online ? styles['avatar__status--online'] : styles['avatar__status--offline'])}
        />
      )}
    </div>
  );
};
