import React from 'react';
import { StyleSheet, Image, ImageProps, View } from 'react-native';
import ThemedText from '@/components/theme/default/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

type ThemedAvatarProps = Omit<ImageProps, 'source'> & {
  size?: number;
  source?: ImageProps['source'];
  name?: string;
  borderWidth?: number;
  borderColor?: string;
};

const ThemedAvatar: React.FC<ThemedAvatarProps> = ({
  size = 50,
  source,
  name,
  borderWidth = 0,
  borderColor,
  style,
  ...restProps
}) => {
  const scheme = useColorScheme() ?? 'dark';
  const border = borderColor || Colors[scheme].tint;

  // Get initials from name
  const getInitials = (name?: string) => {
    if (!name) return '';
    return name
      .split(' ')
      .map((part) => part[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };

  const initials = getInitials(name);

  return (
    <View
      style={[
        styles.container,
        {
          width: size,
          height: size,
          borderRadius: size / 2,
          borderWidth,
          borderColor: border,
          backgroundColor: source ? 'transparent' : Colors[scheme].tint,
        },
      ]}
    >
      {source ? (
        <Image
          source={source}
          style={[
            {
              width: size - 2 * borderWidth,
              height: size - 2 * borderWidth,
              borderRadius: (size - 2 * borderWidth) / 2,
            },
            style,
          ]}
          {...restProps}
        />
      ) : (
        <ThemedText style={{ color: Colors[scheme].background, fontSize: size * 0.4 }}>
          {initials}
        </ThemedText>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden',
  },
});

export default ThemedAvatar;
