import React from 'react';
import {Pressable, StyleProp, ViewStyle} from 'react-native';
import {Avatar, AvatarProps} from '@components/_HuGo/Avatar';
import {TUserName} from '@shared/utils';
import {useTheme} from '@shared/theme';

import {getMarginBySize, styles} from './styles';

export const AVATAR_GROUP_LIST_LIMIT = 3;

export interface AvatarGroupItem {
  id?: number;
  url?: Nullable<string>;
  name?: TUserName;
}

export interface AvatarGroupProps
  extends Omit<AvatarProps, 'url' | 'name' | 'rounded' | 'variant' | 'style'> {
  list: AvatarGroupItem[];
  collapsed?: boolean;
  style?: StyleProp<ViewStyle>;
  onPress?: () => void;
  groupCount?: number;
  limit?: number;
}

export function AvatarGroup({
  list,
  style,
  onPress,
  size = 'md',
  collapsed = true,
  groupCount,
  limit = AVATAR_GROUP_LIST_LIMIT,
  ...props
}: AvatarGroupProps) {
  const {theme} = useTheme();
  const marginLeft = getMarginBySize(size, collapsed);
  const moreItem = (groupCount || list.length) - limit;

  return (
    <Pressable onPress={onPress} style={[styles.container, style]}>
      {list.slice(0, limit).map((user, index) => (
        <Avatar
          key={user.id ? `${user.id}-${index}` : index}
          url={user.url}
          name={user.name}
          size={size}
          style={[
            styles.avatar,
            {
              borderColor: theme.text.neutral.inverted,
              marginLeft: index !== 0 ? marginLeft : undefined,
            },
          ]}
          {...props}
        />
      ))}
      {moreItem > 0 && (
        <Avatar
          size={size}
          style={[
            styles.avatar,
            {borderColor: theme.text.neutral.inverted, marginLeft},
          ]}
          customLabel={`+${moreItem}`}
          {...props}
        />
      )}
    </Pressable>
  );
}
