import React, { useMemo } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { Race } from '../types';
import { formatRaceTime, formatCountdown, formatDistance } from '../utils/formatters';
import { useTheme, Theme } from '../theme/ThemeContext';

interface RaceCardProps {
  race: Race;
  onPress?: () => void;
  showCountdown?: boolean;
  compact?: boolean;
}

const getRacingTypeIcon = (racingType: string): string => {
  switch (racingType) {
    case 'thoroughbred': return 'ribbon';
    case 'harness': return 'car-sport';
    case 'greyhound': return 'paw';
    default: return 'flag';
  }
};

const getRacingTypeColor = (racingType: string): string => {
  switch (racingType) {
    case 'thoroughbred': return '#3b82f6';  // blue
    case 'harness': return '#8b5cf6';       // purple
    case 'greyhound': return '#22c55e';     // green
    default: return '#6b7280';
  }
};

const getRacingTypeLabel = (racingType: string): string => {
  switch (racingType) {
    case 'thoroughbred': return 'Gallops';
    case 'harness': return 'Trots';
    case 'greyhound': return 'Dogs';
    default: return racingType;
  }
};

const createStyles = (theme: Theme) =>
  StyleSheet.create({
    container: {
      backgroundColor: theme.card,
      borderRadius: 12,
      padding: 16,
      marginBottom: 12,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.05,
      shadowRadius: 8,
      elevation: 2,
    },
    containerCompact: {
      padding: 12,
      marginBottom: 8,
    },
    header: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'flex-start',
      marginBottom: 8,
    },
    trackInfo: {
      flex: 1,
    },
    trackRow: {
      flexDirection: 'row',
      marginBottom: 4,
    },
    racingTypeBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: 8,
      paddingVertical: 3,
      borderRadius: 10,
      gap: 4,
    },
    racingTypeText: {
      fontSize: 11,
      fontWeight: '600',
    },
    trackName: {
      fontSize: 18,
      fontWeight: '700',
      color: theme.text,
    },
    raceNumber: {
      fontSize: 14,
      color: theme.textSecondary,
      marginTop: 2,
    },
    countdown: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: theme.chipBg,
      paddingHorizontal: 10,
      paddingVertical: 6,
      borderRadius: 20,
      gap: 4,
    },
    countdownSoon: {
      backgroundColor: '#dc2626',
    },
    countdownText: {
      fontSize: 14,
      fontWeight: '600',
      color: theme.chipText,
    },
    countdownTextSoon: {
      color: '#fff',
    },
    details: {
      flexDirection: 'row',
      gap: 16,
      marginBottom: 12,
    },
    detailItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
    },
    detailText: {
      fontSize: 13,
      color: theme.textSecondary,
    },
    footer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    time: {
      fontSize: 15,
      fontWeight: '600',
      color: theme.text,
    },
    runnerCount: {
      fontSize: 13,
      color: theme.textTertiary,
    },
  });

export const RaceCard: React.FC<RaceCardProps> = ({
  race,
  onPress,
  showCountdown = true,
  compact = false,
}) => {
  const { theme } = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const countdown = formatCountdown(race.start_time);
  const isStartingSoon = countdown.includes('m') && !countdown.includes('h');
  const racingType = race.racing_type || 'thoroughbred';

  return (
    <TouchableOpacity
      style={[styles.container, compact && styles.containerCompact]}
      onPress={onPress}
      activeOpacity={0.7}
    >
      <View style={styles.header}>
        <View style={styles.trackInfo}>
          <View style={styles.trackRow}>
            <View style={[styles.racingTypeBadge, { backgroundColor: getRacingTypeColor(racingType) + '20' }]}>
              <Ionicons
                name={getRacingTypeIcon(racingType) as any}
                size={12}
                color={getRacingTypeColor(racingType)}
              />
              <Text style={[styles.racingTypeText, { color: getRacingTypeColor(racingType) }]}>
                {getRacingTypeLabel(racingType)}
              </Text>
            </View>
          </View>
          <Text style={styles.trackName}>{race.track}</Text>
          <Text style={styles.raceNumber}>Race {race.race_number}</Text>
        </View>
        {showCountdown && (
          <View style={[styles.countdown, isStartingSoon && styles.countdownSoon]}>
            <Ionicons
              name="time-outline"
              size={14}
              color={isStartingSoon ? '#fff' : theme.textSecondary}
            />
            <Text style={[styles.countdownText, isStartingSoon && styles.countdownTextSoon]}>
              {countdown}
            </Text>
          </View>
        )}
      </View>

      {!compact && (
        <View style={styles.details}>
          <View style={styles.detailItem}>
            <Ionicons name="navigate-outline" size={14} color={theme.textTertiary} />
            <Text style={styles.detailText}>{formatDistance(race.distance)}</Text>
          </View>
          <View style={styles.detailItem}>
            <Ionicons name="trophy-outline" size={14} color={theme.textTertiary} />
            <Text style={styles.detailText}>{race.race_class}</Text>
          </View>
          <View style={styles.detailItem}>
            <Ionicons name="cloudy-outline" size={14} color={theme.textTertiary} />
            <Text style={styles.detailText}>{race.conditions}</Text>
          </View>
        </View>
      )}

      <View style={styles.footer}>
        <Text style={styles.time}>{formatRaceTime(race.start_time)}</Text>
        {race.runner_count && (
          <Text style={styles.runnerCount}>{race.runner_count} runners</Text>
        )}
      </View>
    </TouchableOpacity>
  );
};