import { useState } from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { useDubsTheme } from '../theme';
import { ensurePngAvatar } from '../../utils/avatarUrl';
import type { GameDetail } from '../../types';

export interface PlayersCardProps {
  game: GameDetail;
  /** How many chars to show on each side of a truncated wallet. Default 4. */
  truncateChars?: number;
  /** Override team dot colors. */
  homeColor?: string;
  awayColor?: string;
  drawColor?: string;
  /** Optional Image component (expo-image, etc.). */
  ImageComponent?: React.ComponentType<any>;
}

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

/**
 * Card showing all bettors in a game with their avatar, username, team, and wager amount.
 */
export function PlayersCard({
  game,
  truncateChars = 4,
  homeColor = '#3B82F6',
  awayColor = '#EF4444',
  drawColor = '#A855F7',
  ImageComponent,
}: PlayersCardProps) {
  const t = useDubsTheme();
  const bettors = game.bettors || [];

  const dotColor = (team: 'home' | 'away' | 'draw') => {
    if (team === 'home') return homeColor;
    if (team === 'away') return awayColor;
    return drawColor;
  };

  return (
    <View style={[styles.card, { backgroundColor: t.surface, borderColor: t.border }]}>
      <Text style={[styles.title, { color: t.text }]}>
        Players{bettors.length > 0 ? ` (${bettors.length})` : ''}
      </Text>

      {bettors.length === 0 ? (
        <Text style={[styles.empty, { color: t.textMuted }]}>No players yet — be the first!</Text>
      ) : (
        bettors.map((b, i) => (
          <BettorRow
            key={`${b.wallet}-${i}`}
            bettor={b}
            dotColor={dotColor(b.team)}
            truncateChars={truncateChars}
            isFirst={i === 0}
            ImageComponent={ImageComponent}
            t={t}
          />
        ))
      )}
    </View>
  );
}

function BettorRow({
  bettor, dotColor, truncateChars, isFirst, ImageComponent, t,
}: {
  bettor: { wallet: string; username: string | null; avatar: string | null; team: 'home' | 'away' | 'draw'; amount: number };
  dotColor: string; truncateChars: number; isFirst: boolean;
  ImageComponent?: React.ComponentType<any>; t: any;
}) {
  const [imgFailed, setImgFailed] = useState(false);
  const Img = ImageComponent || require('react-native').Image;
  const showAvatar = bettor.avatar && !imgFailed;

  return (
    <View style={[styles.row, !isFirst && { borderTopColor: t.border, borderTopWidth: 1 }]}>
      <View style={[styles.dot, { backgroundColor: dotColor }]} />
      {showAvatar ? (
        <Img source={{ uri: ensurePngAvatar(bettor.avatar) }} style={styles.avatar} resizeMode="cover" onError={() => setImgFailed(true)} />
      ) : (
        <View style={[styles.avatar, styles.avatarPlaceholder]} />
      )}
      <View style={styles.nameCol}>
        <Text style={[styles.username, { color: t.text }]} numberOfLines={1}>
          {bettor.username || truncateWallet(bettor.wallet, truncateChars)}
        </Text>
      </View>
      <Text style={[styles.amount, { color: t.textSecondary }]}>{bettor.amount} SOL</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  card: { borderRadius: 16, borderWidth: 1, padding: 16 },
  title: { fontSize: 17, fontWeight: '700', marginBottom: 12 },
  empty: { fontSize: 14, textAlign: 'center', paddingVertical: 16 },
  row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 10, gap: 10 },
  dot: { width: 8, height: 8, borderRadius: 4 },
  avatar: { width: 28, height: 28, borderRadius: 14 },
  avatarPlaceholder: { backgroundColor: 'rgba(128,128,128,0.2)' },
  nameCol: { flex: 1 },
  username: { fontSize: 14, fontWeight: '600' },
  amount: { fontSize: 13, fontWeight: '700' },
});
