import React from 'react';
import { themedColor } from '../../theme';
import { Image, Text, View } from 'react-native';
import { User } from 'lucide-react-native';
import { SvgXml } from 'react-native-svg';

import { agentAvatarSvg } from './agentAvatarAssets';
import { agentSphereStyles } from './agentSphereStyles';
import type { SuperagentAgent } from '../../types';

const SIZES = { xl: 56, lg: 48, header: 34, md: 30, sm: 24 };

export function AgentSphereIcon({
  agent,
  isUser = false,
  size = 'md',
  userAvatarUrl,
}: {
  agent?: SuperagentAgent;
  isUser?: boolean;
  size?: keyof typeof SIZES | number;
  userAvatarUrl?: string | null;
}) {
  const dimension = typeof size === 'number' ? size : SIZES[size];
  const borderRadius = dimension / 2;
  const logo = getAgentLogo(agent);
  const [userImageFailed, setUserImageFailed] = React.useState(false);
  const normalizedUserAvatarUrl = userAvatarUrl?.trim();

  React.useEffect(() => {
    setUserImageFailed(false);
  }, [normalizedUserAvatarUrl]);

  if (isUser) {
    if (normalizedUserAvatarUrl && !userImageFailed) {
      return (
        <View style={[
          agentSphereStyles.frame,
          agentSphereStyles.userFrame,
          { borderRadius, height: dimension, width: dimension },
        ]}>
          <Image
            onError={() => setUserImageFailed(true)}
            resizeMode="cover"
            source={{ uri: normalizedUserAvatarUrl }}
            style={agentSphereStyles.image}
          />
        </View>
      );
    }

    return (
      <View style={[
        agentSphereStyles.frame,
        agentSphereStyles.userFrame,
        { borderRadius, height: dimension, width: dimension },
      ]}>
        <User color={themedColor('#D4D4D8')} size={dimension * 0.48} strokeWidth={2.4} />
      </View>
    );
  }

  if (logo.emoji) {
    return (
      <View style={[
        agentSphereStyles.frame,
        agentSphereStyles.emojiFrame,
        { borderRadius, height: dimension, width: dimension },
      ]}>
        <Text style={[agentSphereStyles.emoji, { fontSize: dimension * 0.48, lineHeight: dimension * 0.62 }]}>
          {logo.emoji}
        </Text>
      </View>
    );
  }

  if (logo.url) {
    return (
      <View style={[
        agentSphereStyles.frame,
        { borderRadius, height: dimension, width: dimension },
      ]}>
        <Image resizeMode="cover" source={{ uri: logo.url }} style={agentSphereStyles.image} />
      </View>
    );
  }

  // DS "Agent Avatar" blob (picked by avatarIndex) — a free-form multi-color
  // illustration with its own silhouette + transparent margins, so it renders
  // directly at `dimension` with no circular frame/background behind it.
  return (
    <View style={[agentSphereStyles.frame, { height: dimension, width: dimension }]}>
      <SvgXml xml={agentAvatarSvg(agent?.avatarIndex)} width={dimension} height={dimension} />
    </View>
  );
}

function getAgentLogo(agent?: SuperagentAgent) {
  const logoUrl = agent?.logoUrl?.trim();
  if (logoUrl?.startsWith('emoji:')) {
    return { emoji: logoUrl.replace('emoji:', ''), url: null };
  }

  return {
    emoji: agent?.emoji?.trim() || null,
    url: logoUrl || null,
  };
}
