import React from 'react';
import {View, Image, StyleSheet, Text} from 'react-native';
import {SwipeableListItemAvatarProps} from './types';
import {useTheme, ColorsScheme} from '../../theme/ThemeContext';
import PlayyText from '../PlayyText/PlayyText';

/**
 * Avatar section of SwipeableListItem
 * Accepts all Image props plus custom size, style, and fallbackName
 * 
 * @example
 * ```tsx
 * // With image
 * <SwipeableListItem.Avatar 
 *   source={{uri: 'https://...'}} 
 *   fallbackName="John Doe"
 *   resizeMode="cover"
 * />
 * 
 * // Fallback with initials
 * <SwipeableListItem.Avatar fallbackName="John Doe" />
 * ```
 */
export const SwipeableListItemAvatar: React.FC<SwipeableListItemAvatarProps> = ({
  source,
  fallbackName,
  size = 56,
  style,
  ...imageProps
}) => {
  const {colors} = useTheme();
  const styles = themedStyle(colors);

  // Get initials from fallbackName
  const getInitials = (name: string): string => {
    const parts = name.trim().split(' ').filter(Boolean);
    if (parts.length === 0) return '?';
    if (parts.length === 1) return parts[0][0].toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  };

  return (
    <View style={[styles.avatarContainer, style]}>
      {source ? (
        <Image 
          source={source} 
          style={[styles.avatar, {width: size, height: size, borderRadius: size / 2}]} 
          {...imageProps}
        />
      ) : (
        <View style={[styles.avatar, styles.avatarPlaceholder, {width: size, height: size, borderRadius: size / 2}]}>
          {fallbackName && (
            <PlayyText 
              BodyEmphasized 
              color={colors.labels_secondary}
            >
              {getInitials(fallbackName)}
            </PlayyText>
          )}
        </View>
      )}
    </View>
  );
};

const themedStyle = (colors: ColorsScheme) =>
  StyleSheet.create({
    avatarContainer: {
      marginRight: 12.66,
    },
    avatar: {
      width: 56,
      height: 56,
      borderRadius: 50,
    },
    avatarPlaceholder: {
      backgroundColor: colors.fill_tertiary,
      justifyContent: 'center',
      alignItems: 'center',
    },
  });
