import React from 'react';
import { Image, StyleSheet, View } from 'react-native';

import { ThemedView } from '@/components/themed-view';
import { ThemedText } from '@/components/themed-text';
import { useThemeColor } from '@/hooks/use-theme-color';

interface UserAvatarProps {
  image?: string;
  name: string;
  size?: number;
  showBorder?: boolean;
}

export function UserAvatar({
  image,
  name,
  size = 40,
  showBorder = true
}: UserAvatarProps) {
  const borderColor = useThemeColor({}, 'cardBorder');
  const placeholderColor = useThemeColor({}, 'imagePlaceholder');
  const textColor = useThemeColor({}, 'text');

  const avatarSize = size;
  const borderRadius = avatarSize / 2;
  const fontSize = avatarSize / 3;

  const getInitials = (name: string) => {
    return name
      .split(' ')
      .map(word => word[0])
      .join('')
      .toUpperCase()
      .slice(0, 2);
  };

  return (
    <View
      style={[
        styles.container,
        {
          width: avatarSize,
          height: avatarSize,
          borderRadius,
          borderColor: showBorder ? borderColor : 'transparent',
        }
      ]}
    >
      {image ? (
        <Image
          source={{ uri: image }}
          style={[
            styles.image,
            {
              width: avatarSize - 4,
              height: avatarSize - 4,
              borderRadius: (avatarSize - 4) / 2,
            }
          ]}
          resizeMode="cover"
        />
      ) : (
        <ThemedView
          style={[
            styles.placeholder,
            {
              width: avatarSize - 4,
              height: avatarSize - 4,
              borderRadius: (avatarSize - 4) / 2,
              backgroundColor: placeholderColor,
            }
          ]}
        >
          <ThemedText
            style={[
              styles.initials,
              {
                fontSize,
                color: textColor,
              }
            ]}
          >
            {getInitials(name)}
          </ThemedText>
        </ThemedView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    borderWidth: 2,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
  },
  image: {
    backgroundColor: 'transparent',
  },
  placeholder: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  initials: {
    fontWeight: '600',
    textAlign: 'center',
  },
});