import React, { useMemo } from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import { useDubsTheme } from './theme';
import { ensurePngAvatar } from '../utils/avatarUrl';

export interface UserProfileCardProps {
  walletAddress: string;
  username?: string;
  avatarUrl?: string | null;
  memberSince?: string | null;
}

function truncateAddress(address: string, chars = 4): string {
  if (address.length <= chars * 2 + 3) return address;
  return `${address.slice(0, chars)}...${address.slice(-chars)}`;
}

function formatMemberSince(iso: string): string {
  const date = new Date(iso);
  const month = date.toLocaleString('en-US', { month: 'short' });
  const year = date.getFullYear();
  return `Member since ${month} ${year}`;
}

export function UserProfileCard({
  walletAddress,
  username,
  avatarUrl,
  memberSince,
}: UserProfileCardProps) {
  const t = useDubsTheme();

  const imageUri = useMemo(
    () =>
      ensurePngAvatar(avatarUrl) ||
      `https://api.dicebear.com/9.x/avataaars/png?seed=${walletAddress}&size=128`,
    [avatarUrl, walletAddress],
  );

  return (
    <View style={[styles.card, { backgroundColor: t.surface, borderColor: t.border }]}>
      <Image source={{ uri: imageUri }} style={styles.avatar} />
      <View style={styles.info}>
        {username ? (
          <Text style={[styles.username, { color: t.text }]}>{username}</Text>
        ) : null}
        <Text style={[styles.address, { color: t.textMuted }]}>
          {truncateAddress(walletAddress)}
        </Text>
        {memberSince ? (
          <Text style={[styles.memberSince, { color: t.textDim }]}>
            {formatMemberSince(memberSince)}
          </Text>
        ) : null}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderRadius: 16,
    borderWidth: 1,
    gap: 14,
  },
  avatar: {
    width: 64,
    height: 64,
    borderRadius: 32,
    backgroundColor: '#1A1A24',
  },
  info: {
    flex: 1,
    gap: 2,
  },
  username: {
    fontSize: 18,
    fontWeight: '700',
  },
  address: {
    fontSize: 14,
    fontFamily: 'monospace',
  },
  memberSince: {
    fontSize: 12,
    marginTop: 2,
  },
});
