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

export interface PickWinnerCardProps {
  game: GameDetail;
  selectedTeam: 'home' | 'away' | null;
  onSelect: (team: 'home' | 'away') => void;
  /** Custom short-name function for team labels. Defaults to full name. */
  shortName?: (name: string | null) => string;
  /** Override colors. Defaults to blue/red. */
  homeColor?: string;
  awayColor?: string;
  /** Optional Image component (expo-image, etc.). */
  ImageComponent?: React.ComponentType<any>;
}

/**
 * Team selection card for picking which side to bet on.
 */
export function PickWinnerCard({
  game,
  selectedTeam,
  onSelect,
  shortName,
  homeColor = '#3B82F6',
  awayColor = '#EF4444',
  ImageComponent,
}: PickWinnerCardProps) {
  const t = useDubsTheme();

  const opponents = game.opponents || [];
  const bettors = game.bettors || [];
  const totalPool = game.totalPool || 0;
  const homePool = game.homePool || 0;
  const awayPool = game.awayPool || 0;

  const { homeOdds, awayOdds, homeBets, awayBets } = useMemo(() => ({
    homeOdds: homePool > 0 ? (totalPool / homePool).toFixed(2) : '—',
    awayOdds: awayPool > 0 ? (totalPool / awayPool).toFixed(2) : '—',
    homeBets: bettors.filter(b => b.team === 'home').length,
    awayBets: bettors.filter(b => b.team === 'away').length,
  }), [totalPool, homePool, awayPool, bettors]);

  const homeName = shortName ? shortName(opponents[0]?.name) : (opponents[0]?.name || 'Home');
  const awayName = shortName ? shortName(opponents[1]?.name) : (opponents[1]?.name || 'Away');

  return (
    <View style={[styles.card, { backgroundColor: t.surface, borderColor: t.border }]}>
      <Text style={[styles.title, { color: t.text }]}>Pick Your Winner</Text>
      <View style={styles.row}>
        <TeamOption
          name={homeName}
          imageUrl={opponents[0]?.imageUrl}
          odds={homeOdds}
          bets={homeBets}
          color={homeColor}
          selected={selectedTeam === 'home'}
          onPress={() => onSelect('home')}
          ImageComponent={ImageComponent}
          t={t}
        />
        <TeamOption
          name={awayName}
          imageUrl={opponents[1]?.imageUrl}
          odds={awayOdds}
          bets={awayBets}
          color={awayColor}
          selected={selectedTeam === 'away'}
          onPress={() => onSelect('away')}
          ImageComponent={ImageComponent}
          t={t}
        />
      </View>
    </View>
  );
}

function TeamOption({
  name, imageUrl, odds, bets, color, selected, onPress, ImageComponent, t,
}: {
  name: string; imageUrl?: string | null; odds: string; bets: number;
  color: string; selected: boolean; onPress: () => void;
  ImageComponent?: React.ComponentType<any>; t: any;
}) {
  const [imgFailed, setImgFailed] = useState(false);
  const Img = ImageComponent || require('react-native').Image;
  const showImage = imageUrl && !imgFailed;

  return (
    <TouchableOpacity
      style={[styles.option, { borderColor: selected ? color : t.border, backgroundColor: selected ? color + '15' : t.background }]}
      onPress={onPress}
      activeOpacity={0.7}
    >
      {showImage ? (
        <Img source={{ uri: imageUrl }} style={styles.logo} resizeMode="contain" onError={() => setImgFailed(true)} />
      ) : (
        <View style={[styles.logo, styles.logoPlaceholder]} />
      )}
      <Text style={[styles.name, { color: t.text }]} numberOfLines={1}>{name}</Text>
      <Text style={[styles.odds, { color }]}>{odds}x</Text>
      <Text style={[styles.bets, { color: t.textMuted }]}>{bets} {bets === 1 ? 'bet' : 'bets'}</Text>
      {selected && (
        <View style={[styles.badge, { backgroundColor: color }]}>
          <Text style={styles.badgeText}>Selected</Text>
        </View>
      )}
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  card: { borderRadius: 16, borderWidth: 1, padding: 16 },
  title: { fontSize: 17, fontWeight: '700', marginBottom: 12 },
  row: { flexDirection: 'row', gap: 12 },
  option: { flex: 1, borderWidth: 2, borderRadius: 16, padding: 16, alignItems: 'center', gap: 8 },
  logo: { width: 48, height: 48, borderRadius: 24 },
  logoPlaceholder: { backgroundColor: 'rgba(128,128,128,0.2)' },
  name: { fontSize: 15, fontWeight: '700' },
  odds: { fontSize: 20, fontWeight: '800' },
  bets: { fontSize: 12 },
  badge: { borderRadius: 8, paddingHorizontal: 12, paddingVertical: 4, marginTop: 4 },
  badgeText: { color: '#FFF', fontSize: 12, fontWeight: '700' },
});
