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

export interface JoinGameButtonProps {
  game: GameDetail;
  walletAddress: string;
  selectedTeam: 'home' | 'away' | null;
  status: MutationStatus;
  onJoin: () => void;
}

const STATUS_LABELS: Record<string, string> = {
  building: 'Building transaction...',
  signing: 'Approve in wallet...',
  confirming: 'Confirming on-chain...',
  saving: 'Saving...',
};

/**
 * Fixed bottom bar with buy-in info and join button.
 * Renders nothing if the user already joined, or the game is locked/resolved.
 */
export function JoinGameButton({ game, walletAddress, selectedTeam, status, onJoin }: JoinGameButtonProps) {
  const t = useDubsTheme();

  const alreadyJoined = useMemo(() => {
    if (!walletAddress) return false;
    return (game.bettors || []).some(b => b.wallet === walletAddress);
  }, [game.bettors, walletAddress]);

  if (alreadyJoined || game.isLocked || game.isResolved) return null;

  const isJoining = status !== 'idle' && status !== 'success' && status !== 'error';
  const statusLabel = STATUS_LABELS[status] || '';

  return (
    <View style={[styles.bar, { backgroundColor: t.background, borderTopColor: t.border }]}>
      <View style={styles.buyInRow}>
        <Text style={[styles.buyInLabel, { color: t.textMuted }]}>Buy-in</Text>
        <Text style={[styles.buyInValue, { color: t.text }]}>{game.buyIn} SOL</Text>
      </View>
      <TouchableOpacity
        style={[styles.button, { backgroundColor: selectedTeam ? t.accent : t.border }]}
        disabled={!selectedTeam || isJoining}
        onPress={onJoin}
        activeOpacity={0.8}
      >
        {isJoining ? (
          <View style={styles.joiningRow}>
            <ActivityIndicator size="small" color="#000" />
            <Text style={styles.buttonText}>{statusLabel}</Text>
          </View>
        ) : (
          <Text style={[styles.buttonText, !selectedTeam && { color: t.textMuted }]}>
            {selectedTeam ? `Join Bet — ${game.buyIn} SOL` : 'Pick a team to bet'}
          </Text>
        )}
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  bar: { position: 'absolute', bottom: 0, left: 0, right: 0, paddingHorizontal: 16, paddingTop: 12, paddingBottom: 36, borderTopWidth: 1 },
  buyInRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 },
  buyInLabel: { fontSize: 13 },
  buyInValue: { fontSize: 15, fontWeight: '800' },
  button: { borderRadius: 14, paddingVertical: 16, alignItems: 'center' },
  buttonText: { color: '#000', fontSize: 16, fontWeight: '800' },
  joiningRow: { flexDirection: 'row', alignItems: 'center', gap: 10 },
});
