import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams, useRouter, Stack } from 'expo-router';
import { getRace, generateTip } from '../../src/services/api';
import { Race, Runner, Tip } from '../../src/types';
import { formatRaceTime, formatCountdown, formatDistance, formatPrizeMoney } from '../../src/utils/formatters';
import { ConfidenceMeter } from '../../src/components/ConfidenceMeter';
import { useTheme, Theme } from '../../src/theme/ThemeContext';
import { useAppStore } from '../../src/store/appStore';
import { analytics } from '../../src/analytics';
import { useScreenTracking } from '../../src/analytics/useAnalytics';

// ── Helpers ──────────────────────────────────────────────────────────────

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';
    case 'harness': return '#8b5cf6';
    case 'greyhound': return '#22c55e';
    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 getOddsColor = (odds: number): string => {
  if (odds <= 3) return '#22c55e';     // Favourite
  if (odds <= 10) return '#3b82f6';    // Contender
  if (odds <= 20) return '#eab308';    // Roughie
  return '#ef4444';                     // Long shot
};

// ── Runner Detail Row ────────────────────────────────────────────────────

interface RunnerDetailRowProps {
  runner: Runner;
  theme: Theme;
  onPress?: () => void;
  isTopPick?: boolean;
}

const RunnerDetailRow: React.FC<RunnerDetailRowProps> = ({ runner, theme, onPress, isTopPick }) => {
  const s = useMemo(() => createStyles(theme), [theme]);

  return (
    <TouchableOpacity
      style={[s.runnerContainer, isTopPick && s.runnerContainerTopPick]}
      onPress={onPress}
      activeOpacity={0.7}
    >
      {/* Top pick indicator */}
      {isTopPick && (
        <View style={s.topPickBadge}>
          <Ionicons name="star" size={12} color="#fff" />
          <Text style={s.topPickText}>TOP PICK</Text>
        </View>
      )}

      <View style={s.runnerHeader}>
        {/* Barrier / Number */}
        <View style={[s.barrierBadge, isTopPick && s.barrierBadgeTopPick]}>
          <Text style={[s.barrierNumber, isTopPick && s.barrierNumberTopPick]}>
            {runner.number}
          </Text>
        </View>

        {/* Name + Rider/Trainer */}
        <View style={s.runnerInfo}>
          <Text style={s.runnerName} numberOfLines={1}>
            {runner.name}
          </Text>
          <Text style={s.runnerMeta} numberOfLines={1}>
            {runner.rider ? `${runner.rider} \u2022 ` : ''}{runner.trainer}
            {runner.weight ? ` \u2022 ${runner.weight}kg` : ''}
          </Text>
        </View>

        {/* Odds */}
        <View style={[s.oddsBadge, { backgroundColor: getOddsColor(runner.odds ?? 99) + '20' }]}>
          <Text style={[s.oddsText, { color: getOddsColor(runner.odds ?? 99) }]}>
            ${runner.odds?.toFixed(1)}
          </Text>
        </View>
      </View>

      {/* Stats row: Elo, win prob, place prob */}
      <View style={s.statsRow}>
        {runner.elo_rating != null && (
          <View style={s.statItem}>
            <Ionicons name="trending-up" size={13} color={theme.textTertiary} />
            <Text style={s.statLabel}>Elo</Text>
            <Text style={s.statValue}>{runner.elo_rating.toFixed(0)}</Text>
          </View>
        )}
        <View style={s.statItem}>
          <Ionicons name="flag" size={13} color={theme.textTertiary} />
          <Text style={s.statLabel}>Win</Text>
          <Text style={s.statValue}>{runner.win_probability.toFixed(1)}%</Text>
        </View>
        <View style={s.statItem}>
          <Ionicons name="podium" size={13} color={theme.textTertiary} />
          <Text style={s.statLabel}>Place</Text>
          <Text style={s.statValue}>{runner.place_probability.toFixed(1)}%</Text>
        </View>
        <View style={s.statItem}>
          <Ionicons name="grid" size={13} color={theme.textTertiary} />
          <Text style={s.statLabel}>Barrier</Text>
          <Text style={s.statValue}>{runner.barrier}</Text>
        </View>
      </View>

      {/* Badges */}
      {(runner.badges?.length ?? 0) > 0 && (
        <View style={s.badgesRow}>
          {runner.badges.map((badge, i) => (
            <View key={i} style={s.badge}>
              <Text style={s.badgeText}>{badge}</Text>
            </View>
          ))}
        </View>
      )}
    </TouchableOpacity>
  );
};

// ── Main Screen ──────────────────────────────────────────────────────────

export default function RaceDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const router = useRouter();
  const { theme } = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const { setSelectedRace, setSelectedBetType } = useAppStore();

  useScreenTracking('race_detail');

  const [race, setRace] = useState<Race | null>(null);
  const [tip, setTip] = useState<Tip | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [generatingTip, setGeneratingTip] = useState(false);

  const loadRace = useCallback(async () => {
    if (!id) return;
    try {
      setError(null);
      const data = await getRace(id);
      setRace(data);
    } catch (err) {
      console.error('Error loading race:', err);
      setError('Failed to load race details. Pull down to retry.');
    } finally {
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    loadRace();
  }, [loadRace]);

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await loadRace();
    setRefreshing(false);
  }, [loadRace]);

  const handleGetTip = useCallback(async () => {
    if (!race) return;
    setGeneratingTip(true);
    try {
      const generatedTip = await generateTip(race.id, 'best_bet');
      setTip(generatedTip);
      analytics.track('tip_generated', { race_id: race.id, bet_type: 'best_bet' });
    } catch (err) {
      console.error('Error generating tip:', err);
    } finally {
      setGeneratingTip(false);
    }
  }, [race]);

  const handleNavigateToTipBuilder = useCallback(() => {
    if (race) {
      setSelectedRace(race);
      setSelectedBetType('best_bet');
      analytics.track('race_selected', { race_id: race.id, racing_type: race.racing_type });
      router.push('/tip-builder');
    }
  }, [race, setSelectedRace, setSelectedBetType, router]);

  // ── Loading state ──
  if (loading) {
    return (
      <SafeAreaView style={styles.container} edges={['top']}>
        <Stack.Screen options={{ title: 'Race Details', headerShown: false }} />
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={theme.primary} />
          <Text style={styles.loadingText}>Loading race details...</Text>
        </View>
      </SafeAreaView>
    );
  }

  // ── Error state ──
  if (error || !race) {
    return (
      <SafeAreaView style={styles.container} edges={['top']}>
        <Stack.Screen options={{ title: 'Race Details', headerShown: false }} />
        <View style={styles.errorContainer}>
          <Ionicons name="alert-circle-outline" size={56} color={theme.danger} />
          <Text style={styles.errorTitle}>Something went wrong</Text>
          <Text style={styles.errorMessage}>{error || 'Race not found'}</Text>
          <TouchableOpacity style={styles.retryButton} onPress={onRefresh}>
            <Ionicons name="refresh" size={18} color="#fff" />
            <Text style={styles.retryButtonText}>Retry</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }

  const racingType = race.racing_type || 'thoroughbred';
  const isCountdownUrgent = (() => {
    if (!race.start_time) return false;
    const diff = new Date(race.start_time).getTime() - Date.now();
    return diff > 0 && diff < 5 * 60 * 1000;
  })();

  // Sort runners: top pick first (highest win prob), then by barrier
  const sortedRunners = [...(race.runners || [])].sort((a, b) => b.win_probability - a.win_probability);
  const topPick = sortedRunners[0];

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <Stack.Screen
        options={{
          headerShown: true,
          headerTitle: `${race.track} - Race ${race.race_number}`,
          headerBackTitle: 'Back',
          headerStyle: { backgroundColor: theme.background },
          headerTintColor: theme.text,
          headerTitleStyle: { fontWeight: '700', fontSize: 17 },
        }}
      />

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
        showsVerticalScrollIndicator={false}
      >
        {/* ── Race Header Card ── */}
        <View style={styles.headerCard}>
          <View style={styles.headerTop}>
            <View style={[styles.racingTypeBadge, { backgroundColor: getRacingTypeColor(racingType) + '20' }]}>
              <Ionicons name={getRacingTypeIcon(racingType) as any} size={14} color={getRacingTypeColor(racingType)} />
              <Text style={[styles.racingTypeText, { color: getRacingTypeColor(racingType) }]}>
                {getRacingTypeLabel(racingType)}
              </Text>
            </View>
            <View style={[styles.countdownBadge, isCountdownUrgent && styles.countdownUrgent]}>
              <Ionicons
                name="time-outline"
                size={14}
                color={isCountdownUrgent ? '#fff' : theme.textSecondary}
              />
              <Text style={[styles.countdownText, isCountdownUrgent && styles.countdownTextUrgent]}>
                {formatCountdown(race.start_time)}
              </Text>
            </View>
          </View>

          <Text style={styles.meetingName}>{race.track}</Text>
          <Text style={styles.raceSubtitle}>Race {race.race_number}</Text>

          <View style={styles.raceMetaRow}>
            <View style={styles.metaItem}>
              <Ionicons name="navigate-outline" size={15} color={theme.textTertiary} />
              <Text style={styles.metaText}>{formatDistance(race.distance)}</Text>
            </View>
            <View style={styles.metaItem}>
              <Ionicons name="trophy-outline" size={15} color={theme.textTertiary} />
              <Text style={styles.metaText}>{race.race_class}</Text>
            </View>
            <View style={styles.metaItem}>
              <Ionicons name="cloudy-outline" size={15} color={theme.textTertiary} />
              <Text style={styles.metaText}>{race.conditions}</Text>
            </View>
          </View>

          <View style={styles.raceInfoRow}>
            <View style={styles.raceInfoItem}>
              <Text style={styles.raceInfoLabel}>Start Time</Text>
              <Text style={styles.raceInfoValue}>{formatRaceTime(race.start_time)}</Text>
            </View>
            <View style={styles.raceInfoItem}>
              <Text style={styles.raceInfoLabel}>Runners</Text>
              <Text style={styles.raceInfoValue}>{race.runners?.length || 0}</Text>
            </View>
            {race.prize_money != null && (
              <View style={styles.raceInfoItem}>
                <Text style={styles.raceInfoLabel}>Prize</Text>
                <Text style={styles.raceInfoValue}>{formatPrizeMoney(race.prize_money)}</Text>
              </View>
            )}
          </View>
        </View>

        {/* ── Action Buttons ── */}
        <View style={styles.actionRow}>
          <TouchableOpacity style={styles.primaryAction} onPress={handleNavigateToTipBuilder} activeOpacity={0.8}>
            <Ionicons name="flash" size={20} color={theme.primaryText} />
            <Text style={styles.primaryActionText}>Get Tip</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.secondaryAction, generatingTip && styles.actionDisabled]}
            onPress={handleGetTip}
            disabled={generatingTip}
            activeOpacity={0.8}
          >
            <Ionicons
              name={generatingTip ? 'sync' : 'refresh'}
              size={20}
              color={theme.text}
            />
            <Text style={styles.secondaryActionText}>
              {generatingTip ? 'Generating...' : 'Quick Tip'}
            </Text>
          </TouchableOpacity>
        </View>

        {/* ── Tips Section ── */}
        {tip && (
          <View style={styles.tipSection}>
            <Text style={styles.sectionTitle}>Tip</Text>
            <View style={styles.tipCard}>
              <View style={styles.tipHeader}>
                <Ionicons name="bulb" size={22} color="#eab308" />
                <View style={styles.tipInfo}>
                  <Text style={styles.tipBet}>{tip.recommended_bet}</Text>
                  <Text style={styles.tipConfidence}>
                    {tip.confidence.charAt(0).toUpperCase() + tip.confidence.slice(1)} Confidence
                  </Text>
                </View>
              </View>
              <View style={styles.tipConfidenceMeter}>
                <ConfidenceMeter confidence={tip.confidence} showMicroStat={false} />
              </View>
              {tip.reasons && tip.reasons.length > 0 && (
                <View style={styles.tipReasons}>
                  {tip.reasons.slice(0, 3).map((reason, i) => (
                    <View key={i} style={styles.tipReasonRow}>
                      <View
                        style={[
                          styles.reasonDot,
                          reason.type === 'positive' && styles.reasonDotPositive,
                          reason.type === 'caution' && styles.reasonDotCaution,
                        ]}
                      />
                      <Text style={styles.tipReasonText}>{reason.text}</Text>
                    </View>
                  ))}
                </View>
              )}
            </View>
          </View>
        )}

        {/* ── Runners Section ── */}
        <View style={styles.runnersSection}>
          <Text style={styles.sectionTitle}>
            Runners ({race.runners?.length || 0})
          </Text>

          {(race.runners || []).length === 0 ? (
            <View style={styles.noRunners}>
              <Ionicons name="people-outline" size={32} color={theme.textTertiary} />
              <Text style={styles.noRunnersText}>No runner information available</Text>
            </View>
          ) : (
            sortedRunners.map((runner, index) => (
              <RunnerDetailRow
                key={runner.id}
                runner={runner}
                theme={theme}
                isTopPick={index === 0}
              />
            ))
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

// ── Styles ───────────────────────────────────────────────────────────────

const createStyles = (theme: Theme) =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: theme.background,
    },
    loadingContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      gap: 12,
    },
    loadingText: {
      fontSize: 16,
      color: theme.textSecondary,
    },
    errorContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingHorizontal: 32,
      gap: 12,
    },
    errorTitle: {
      fontSize: 20,
      fontWeight: '700',
      color: theme.text,
      marginTop: 8,
    },
    errorMessage: {
      fontSize: 15,
      color: theme.textSecondary,
      textAlign: 'center',
      lineHeight: 22,
    },
    retryButton: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 8,
      backgroundColor: theme.primary,
      paddingHorizontal: 24,
      paddingVertical: 12,
      borderRadius: 12,
      marginTop: 8,
    },
    retryButtonText: {
      fontSize: 15,
      fontWeight: '600',
      color: theme.primaryText,
    },
    scrollView: {
      flex: 1,
    },
    scrollContent: {
      padding: 16,
      paddingBottom: 40,
    },

    /* ── Header Card ── */
    headerCard: {
      backgroundColor: theme.card,
      borderRadius: 16,
      padding: 20,
      marginBottom: 16,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.05,
      shadowRadius: 8,
      elevation: 2,
    },
    headerTop: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 12,
    },
    racingTypeBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingHorizontal: 10,
      paddingVertical: 4,
      borderRadius: 12,
      gap: 5,
    },
    racingTypeText: {
      fontSize: 12,
      fontWeight: '600',
    },
    countdownBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: theme.chipBg,
      paddingHorizontal: 10,
      paddingVertical: 5,
      borderRadius: 16,
      gap: 4,
    },
    countdownUrgent: {
      backgroundColor: theme.danger,
    },
    countdownText: {
      fontSize: 13,
      fontWeight: '600',
      color: theme.chipText,
    },
    countdownTextUrgent: {
      color: '#fff',
    },
    meetingName: {
      fontSize: 24,
      fontWeight: '800',
      color: theme.text,
      marginBottom: 2,
    },
    raceSubtitle: {
      fontSize: 16,
      color: theme.textSecondary,
      marginBottom: 16,
    },
    raceMetaRow: {
      flexDirection: 'row',
      gap: 20,
      marginBottom: 16,
    },
    metaItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 5,
    },
    metaText: {
      fontSize: 14,
      color: theme.textSecondary,
    },
    raceInfoRow: {
      flexDirection: 'row',
      borderTopWidth: 1,
      borderTopColor: theme.borderLight,
      paddingTop: 14,
      gap: 24,
    },
    raceInfoItem: {
      alignItems: 'center',
    },
    raceInfoLabel: {
      fontSize: 11,
      fontWeight: '600',
      color: theme.textTertiary,
      textTransform: 'uppercase',
      marginBottom: 2,
    },
    raceInfoValue: {
      fontSize: 16,
      fontWeight: '700',
      color: theme.text,
    },

    /* ── Action Buttons ── */
    actionRow: {
      flexDirection: 'row',
      gap: 12,
      marginBottom: 20,
    },
    primaryAction: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      gap: 8,
      backgroundColor: theme.primary,
      paddingVertical: 14,
      borderRadius: 12,
    },
    primaryActionText: {
      fontSize: 16,
      fontWeight: '700',
      color: theme.primaryText,
    },
    secondaryAction: {
      flex: 1,
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      gap: 8,
      backgroundColor: theme.card,
      paddingVertical: 14,
      borderRadius: 12,
      borderWidth: 1,
      borderColor: theme.border,
    },
    secondaryActionText: {
      fontSize: 16,
      fontWeight: '600',
      color: theme.text,
    },
    actionDisabled: {
      opacity: 0.6,
    },

    /* ── Tip Section ── */
    tipSection: {
      marginBottom: 20,
    },
    sectionTitle: {
      fontSize: 18,
      fontWeight: '700',
      color: theme.text,
      marginBottom: 12,
    },
    tipCard: {
      backgroundColor: theme.card,
      borderRadius: 14,
      padding: 18,
      borderWidth: 1,
      borderColor: '#eab30840',
    },
    tipHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 12,
      marginBottom: 12,
    },
    tipInfo: {
      flex: 1,
    },
    tipBet: {
      fontSize: 17,
      fontWeight: '700',
      color: theme.text,
    },
    tipConfidence: {
      fontSize: 13,
      color: theme.textSecondary,
      marginTop: 2,
    },
    tipConfidenceMeter: {
      marginBottom: 12,
    },
    tipReasons: {
      borderTopWidth: 1,
      borderTopColor: theme.borderLight,
      paddingTop: 12,
      gap: 8,
    },
    tipReasonRow: {
      flexDirection: 'row',
      alignItems: 'flex-start',
      gap: 8,
    },
    reasonDot: {
      width: 8,
      height: 8,
      borderRadius: 4,
      backgroundColor: theme.textTertiary,
      marginTop: 5,
    },
    reasonDotPositive: {
      backgroundColor: '#22c55e',
    },
    reasonDotCaution: {
      backgroundColor: '#eab308',
    },
    tipReasonText: {
      flex: 1,
      fontSize: 13,
      color: theme.chipText,
      lineHeight: 18,
    },

    /* ── Runners Section ── */
    runnersSection: {
      marginBottom: 16,
    },
    noRunners: {
      alignItems: 'center',
      paddingVertical: 32,
      gap: 8,
    },
    noRunnersText: {
      fontSize: 14,
      color: theme.textTertiary,
    },

    /* ── Runner Row ── */
    runnerContainer: {
      backgroundColor: theme.card,
      borderRadius: 12,
      padding: 14,
      marginBottom: 10,
      borderWidth: 1,
      borderColor: theme.border,
      overflow: 'hidden',
    },
    runnerContainerTopPick: {
      borderColor: '#eab308',
      borderWidth: 1.5,
    },
    topPickBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
      backgroundColor: '#eab308',
      alignSelf: 'flex-start',
      paddingHorizontal: 10,
      paddingVertical: 3,
      borderRadius: 8,
      marginBottom: 10,
    },
    topPickText: {
      fontSize: 10,
      fontWeight: '800',
      color: '#fff',
      letterSpacing: 0.5,
    },
    runnerHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: 10,
    },
    barrierBadge: {
      width: 34,
      height: 34,
      borderRadius: 17,
      backgroundColor: theme.chipBg,
      alignItems: 'center',
      justifyContent: 'center',
      marginRight: 12,
    },
    barrierBadgeTopPick: {
      backgroundColor: '#eab308',
    },
    barrierNumber: {
      fontSize: 15,
      fontWeight: '700',
      color: theme.text,
    },
    barrierNumberTopPick: {
      color: '#fff',
    },
    runnerInfo: {
      flex: 1,
    },
    runnerName: {
      fontSize: 16,
      fontWeight: '600',
      color: theme.text,
    },
    runnerMeta: {
      fontSize: 12,
      color: theme.textSecondary,
      marginTop: 2,
    },
    oddsBadge: {
      paddingHorizontal: 10,
      paddingVertical: 5,
      borderRadius: 10,
      minWidth: 56,
      alignItems: 'center',
    },
    oddsText: {
      fontSize: 14,
      fontWeight: '700',
    },
    statsRow: {
      flexDirection: 'row',
      gap: 16,
      marginBottom: 8,
    },
    statItem: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 3,
    },
    statLabel: {
      fontSize: 11,
      fontWeight: '600',
      color: theme.textTertiary,
    },
    statValue: {
      fontSize: 12,
      fontWeight: '700',
      color: theme.text,
    },
    badgesRow: {
      flexDirection: 'row',
      gap: 6,
      flexWrap: 'wrap',
    },
    badge: {
      backgroundColor: '#fef3c7',
      paddingHorizontal: 8,
      paddingVertical: 3,
      borderRadius: 10,
    },
    badgeText: {
      fontSize: 10,
      fontWeight: '600',
      color: '#92400e',
    },
  });
