import { View, Text } from "react-native";
import { Image } from "expo-image";
import { useTheme } from "../theme";

interface AvatarProps {
  uri?: string | null;
  name: string;
  size?: number;
  borderColor?: string;
}

export function Avatar({ uri, name, size = 48, borderColor }: AvatarProps) {
  const theme = useTheme();
  const initials = name
    .split(" ")
    .map((w) => w[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);

  const baseStyle = {
    width: size,
    height: size,
    borderRadius: size / 2,
    borderWidth: borderColor ? 2 : 0,
    borderColor: borderColor || "transparent",
  };

  if (uri) {
    return (
      <Image
        accessible
        accessibilityLabel={`Аватар на ${name}`}
        source={uri}
        style={baseStyle}
        contentFit="cover"
      />
    );
  }

  return (
    <View
      accessible
      accessibilityLabel={`Аватар на ${name}`}
      style={{
        ...baseStyle,
        backgroundColor: theme.colors.primaryLight,
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Text style={{ color: theme.colors.primary, fontWeight: "700", fontSize: size * 0.4, letterSpacing: 0.5 }}>
        {initials}
      </Text>
    </View>
  );
}
