import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

export interface TeamButtonProps {
  name: string;
  imageUrl?: string | null;
  odds: string;
  bets: number;
  color: string;
  selected: boolean;
  onPress: () => void;
  ImageComponent?: React.ComponentType<any>;
  t: any;
}

export function TeamButton({
  name, imageUrl, odds, bets, color, selected, onPress, ImageComponent, t,
}: TeamButtonProps) {
  const [imgFailed, setImgFailed] = useState(false);
  const Img = ImageComponent || require('react-native').Image;
  const showImage = imageUrl && !imgFailed;

  return (
    <TouchableOpacity
      style={[styles.teamOption, { borderColor: selected ? color : t.border, backgroundColor: selected ? color + '15' : t.background }]}
      onPress={onPress}
      activeOpacity={0.7}
    >
      {showImage ? (
        <Img source={{ uri: imageUrl }} style={styles.teamLogo} resizeMode="contain" onError={() => setImgFailed(true)} />
      ) : (
        <View style={[styles.teamLogo, styles.teamLogoPlaceholder]} />
      )}
      <Text style={[styles.teamName, { color: t.text }]} numberOfLines={1}>{name}</Text>
      {odds !== '—' && <Text style={[styles.teamOdds, { color }]}>{odds}x</Text>}
      {bets > 0 && <Text style={[styles.teamBets, { color: t.textMuted }]}>{bets} {bets === 1 ? 'bet' : 'bets'}</Text>}
      {selected && (
        <View style={[styles.teamBadge, { backgroundColor: color }]}>
          <Text style={styles.teamBadgeText}>Selected</Text>
        </View>
      )}
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  teamOption: {
    flex: 1,
    borderWidth: 2,
    borderRadius: 16,
    padding: 16,
    alignItems: 'center',
    gap: 8,
  },
  teamLogo: {
    width: 48,
    height: 48,
    borderRadius: 24,
  },
  teamLogoPlaceholder: {
    backgroundColor: 'rgba(128,128,128,0.2)',
  },
  teamName: {
    fontSize: 15,
    fontWeight: '700',
  },
  teamOdds: {
    fontSize: 20,
    fontWeight: '800',
  },
  teamBets: {
    fontSize: 12,
  },
  teamBadge: {
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 4,
    marginTop: 4,
  },
  teamBadgeText: {
    color: '#FFF',
    fontSize: 12,
    fontWeight: '700',
  },
});
