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

export interface GamePosterProps {
  game: GameDetail;
  /** Optional Image component — pass expo-image or RN Image. Defaults to RN Image. */
  ImageComponent?: React.ComponentType<any>;
}

function computeCountdown(lockTimestamp: number | string | null): string {
  if (!lockTimestamp) return '';
  const ts = typeof lockTimestamp === 'string' ? parseInt(lockTimestamp) : lockTimestamp;
  const diff = ts * 1000 - Date.now();
  if (diff <= 0) return 'LIVE';
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor((diff % 86400000) / 3600000);
  const mins = Math.floor((diff % 3600000) / 60000);
  if (days > 0) return `${days}d ${hours}h`;
  if (hours > 0) return `${hours}h ${mins}m`;
  return `${mins}m`;
}

/**
 * Matchup poster hero widget.
 * Shows the game poster image (or team logo fallback), countdown pill, and pool total.
 */
export function GamePoster({ game, ImageComponent }: GamePosterProps) {
  const t = useDubsTheme();
  const Img = ImageComponent || require('react-native').Image;

  const opponents = game.opponents || [];
  const home = opponents[0];
  const away = opponents[1];
  const countdown = computeCountdown(game.lockTimestamp);
  const isLive = countdown === 'LIVE';

  return (
    <View style={styles.container}>
      {game.media?.poster ? (
        <Img
          source={{ uri: game.media.poster }}
          style={styles.image}
          resizeMode="cover"
        />
      ) : (
        <View style={[styles.image, { backgroundColor: t.surface }]}>
          <View style={styles.fallback}>
            <TeamLogoInternal url={home?.imageUrl} size={56} Img={Img} />
            <Text style={styles.vs}>VS</Text>
            <TeamLogoInternal url={away?.imageUrl} size={56} Img={Img} />
          </View>
        </View>
      )}
      <View style={styles.overlay} />

      <View style={styles.teamNames}>
        <Text style={styles.teamNameText} numberOfLines={1}>
          {home?.name || 'Home'}
        </Text>
        <Text style={styles.teamNameVs}>vs</Text>
        <Text style={styles.teamNameText} numberOfLines={1}>
          {away?.name || 'Away'}
        </Text>
      </View>

      {countdown ? (
        <View style={styles.countdownPill}>
          <Text style={[styles.countdownText, isLive && styles.countdownLive]}>
            {countdown}
          </Text>
        </View>
      ) : null}

      <View style={styles.poolPill}>
        <Text style={styles.poolText}>{game.totalPool || 0} SOL</Text>
      </View>
    </View>
  );
}

function TeamLogoInternal({ url, size, Img }: { url: string | null | undefined; size: number; Img: any }) {
  const [failed, setFailed] = useState(false);
  if (!url || failed) {
    return <View style={[styles.logoPlaceholder, { width: size, height: size, borderRadius: size / 2 }]} />;
  }
  return (
    <Img
      source={{ uri: url }}
      style={{ width: size, height: size, borderRadius: size / 2 }}
      resizeMode="contain"
      onError={() => setFailed(true)}
    />
  );
}

const styles = StyleSheet.create({
  container: {
    height: 200,
    borderRadius: 16,
    overflow: 'hidden',
    position: 'relative',
  },
  image: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.35)',
  },
  fallback: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 24,
    zIndex: 2,
  },
  vs: {
    color: '#FFF',
    fontSize: 24,
    fontWeight: '900',
    zIndex: 2,
  },
  logoPlaceholder: {
    backgroundColor: 'rgba(255,255,255,0.15)',
    zIndex: 2,
  },
  teamNames: {
    position: 'absolute',
    top: 12,
    left: 12,
    right: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
  },
  teamNameText: {
    color: '#FFF',
    fontSize: 14,
    fontWeight: '700',
    maxWidth: '40%',
  },
  teamNameVs: {
    color: 'rgba(255,255,255,0.6)',
    fontSize: 12,
    fontWeight: '600',
  },
  countdownPill: {
    position: 'absolute',
    bottom: 12,
    left: 12,
    backgroundColor: 'rgba(0,0,0,0.65)',
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 5,
  },
  countdownText: {
    color: '#FFF',
    fontSize: 13,
    fontWeight: '700',
  },
  countdownLive: {
    color: '#EF4444',
  },
  poolPill: {
    position: 'absolute',
    bottom: 12,
    right: 12,
    backgroundColor: '#7C3AED',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 5,
  },
  poolText: {
    color: '#FFF',
    fontSize: 13,
    fontWeight: '800',
  },
});
