import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
  ActivityIndicator,
  Animated,
  Alert,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { RaceCard } from '../../src/components';
import { getRaces, getNextRace, getSavedTips, deleteSavedTip, clearTipCache } from '../../src/services/api';
import { Race } from '../../src/types';
import { useAppStore } from '../../src/store/appStore';
import { usePrefStore } from '../../src/store/prefStore';
import {
  applyPreferenceFilters,
  hasActiveFilters,
  findNextRace,
} from '../../src/utils/filters';
import { formatCountdown } from '../../src/utils/formatters';
import { useTheme, Theme } from '../../src/theme/ThemeContext';
import { useScreenTracking } from '../../src/analytics/useAnalytics';
import { analytics } from '../../src/analytics';

const isRaceUrgent = (race: Race): boolean => {
  const diff = new Date(race.start_time).getTime() - Date.now();
  return diff > 0 && diff < 5 * 60 * 1000;
};

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,
    },
    scrollView: {
      flex: 1,
    },
    scrollContent: {
      padding: 20,
      paddingBottom: 40,
    },
    header: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 24,
    },
    greeting: {
      fontSize: 14,
      color: theme.textSecondary,
      fontWeight: '500',
    },
    title: {
      fontSize: 32,
      fontWeight: '800',
      color: theme.text,
    },
    notificationButton: {
      width: 44,
      height: 44,
      borderRadius: 22,
      backgroundColor: theme.card,
      alignItems: 'center',
      justifyContent: 'center',
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.05,
      shadowRadius: 8,
      elevation: 2,
    },
    primaryCard: {
      backgroundColor: theme.primary,
      borderRadius: 20,
      padding: 24,
      marginBottom: 16,
    },
    primaryCardContent: {
      gap: 8,
    },
    primaryCardTitle: {
      fontSize: 24,
      fontWeight: '800',
      color: '#fff',
    },
    primaryCardSubtitle: {
      fontSize: 15,
      color: theme.textTertiary,
      // Ensure readable contrast on both light (#111827) and dark (#06b6d4) primary backgrounds
    },
    primaryCardBadge: {
      backgroundColor: 'rgba(255,255,255,0.15)',
      alignSelf: 'flex-start',
      paddingHorizontal: 12,
      paddingVertical: 6,
      borderRadius: 20,
      marginTop: 16,
    },
    primaryCardBadgeText: {
      fontSize: 13,
      color: '#fff',
      fontWeight: '600',
    },
    secondaryCard: {
      backgroundColor: theme.card,
      borderRadius: 16,
      padding: 18,
      flexDirection: 'row',
      alignItems: 'center',
      gap: 14,
      marginBottom: 28,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.05,
      shadowRadius: 8,
      elevation: 2,
    },
    secondaryCardContent: {
      flex: 1,
    },
    secondaryCardTitle: {
      fontSize: 16,
      fontWeight: '700',
      color: theme.text,
    },
    secondaryCardSubtitle: {
      fontSize: 13,
      color: theme.textSecondary,
      marginTop: 2,
    },
    section: {
      marginBottom: 24,
    },
    sectionHeader: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 14,
    },
    sectionTitle: {
      fontSize: 18,
      fontWeight: '700',
      color: theme.text,
    },
    seeAllText: {
      fontSize: 14,
      color: '#3b82f6',
      fontWeight: '600',
    },
    horizontalList: {
      paddingRight: 20,
    },
    horizontalCard: {
      width: 280,
      marginRight: 12,
    },
    recentTipCard: {
      backgroundColor: theme.card,
      borderRadius: 12,
      padding: 14,
      marginBottom: 10,
    },
    recentTipHeader: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    recentTipInfo: {
      flex: 1,
      marginRight: 12,
    },
    recentTipBet: {
      fontSize: 15,
      fontWeight: '600',
      color: theme.text,
    },
    recentTipTime: {
      fontSize: 13,
      color: theme.textSecondary,
      marginTop: 2,
    },
    recentTipDelete: {
      width: 32,
      height: 32,
      borderRadius: 8,
      backgroundColor: theme.borderLight,
      alignItems: 'center',
      justifyContent: 'center',
    },
    emptyState: {
      alignItems: 'center',
      padding: 32,
      gap: 8,
    },
    emptyStateTitle: {
      fontSize: 16,
      fontWeight: '600',
      color: theme.textSecondary,
    },
    emptyStateSubtitle: {
      fontSize: 14,
      color: theme.textTertiary,
    },
    primaryCardUrgent: {
      backgroundColor: theme.danger,
    },
    urgentHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 8,
    },
    filterBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
      paddingHorizontal: 10,
      paddingVertical: 4,
      borderRadius: 12,
    },
    filterBadgeText: {
      fontSize: 12,
      fontWeight: '600',
    },
  });

export default function TipsHome() {
  const { theme } = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);

  const router = useRouter();
  const { setSelectedRace, setSelectedBetType } = useAppStore();
  const preferences = usePrefStore((s) => s.preferences);
  const prefsLoaded = usePrefStore((s) => s.loaded);
  const loadPreferences = usePrefStore((s) => s.loadPreferences);
  const getRaceQueryParams = usePrefStore((s) => s.getRaceQueryParams);

  useScreenTracking('home');

  const [nextRace, setNextRace] = useState<Race | null>(null);
  const [upcomingRaces, setUpcomingRaces] = useState<Race[]>([]);
  const [recentTips, setRecentTips] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [pendingPrefs, setPendingPrefs] = useState(false);
  const [countdownText, setCountdownText] = useState('');
  const [deletingTipId, setDeletingTipId] = useState<string | null>(null);
  const pulseAnim = useRef(new Animated.Value(1)).current;

  const isUrgent = nextRace ? isRaceUrgent(nextRace) : false;
  const noRaceSoon = useMemo(() => {
    if (!nextRace) return true;
    const diff = new Date(nextRace.start_time).getTime() - Date.now();
    return diff > 60 * 60 * 1000;
  }, [nextRace]);

  const filtersActive = useMemo(() => hasActiveFilters(preferences), [preferences]);

  const loadData = async () => {
    try {
      // 1. Refresh preferences from API (ensures Profile changes are reflected)
      if (!prefsLoaded) setPendingPrefs(true);
      await loadPreferences();
      setPendingPrefs(false);

      // 2. Read current store state (fresh from step 1)
      const freshPrefs = usePrefStore.getState().preferences;
      const queryParams = usePrefStore.getState().getRaceQueryParams();
      queryParams.limit = 10;

      // 3. Fetch data in parallel
      const [racesData, tipsData, rawNextRace] = await Promise.all([
        getRaces(queryParams),
        getSavedTips().catch(() => []),
        getNextRace().catch(() => null),
      ]);

      // 4. Apply client-side preference filters (handles multi-select cases)
      const filteredRaces = applyPreferenceFilters(racesData, freshPrefs);

      // 5. Find the next race within filtered results
      const filteredNext = findNextRace(filteredRaces);

      // Use filtered next race if available; fall back to unfiltered next race
      setNextRace(filteredNext ?? rawNextRace);
      setUpcomingRaces(filteredRaces);
      setRecentTips(tipsData.slice(0, 5));
    } catch (error) {
      console.error('Error loading data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  // Pulse animation for urgent race state
  useEffect(() => {
    if (isUrgent) {
      const anim = Animated.loop(
        Animated.sequence([
          Animated.timing(pulseAnim, {
            toValue: 0.85,
            duration: 800,
            useNativeDriver: true,
          }),
          Animated.timing(pulseAnim, {
            toValue: 1,
            duration: 800,
            useNativeDriver: true,
          }),
        ])
      );
      anim.start();
      return () => anim.stop();
    } else {
      pulseAnim.setValue(1);
    }
  }, [isUrgent, pulseAnim]);

  // Live countdown timer — updates every second
  useEffect(() => {
    if (!nextRace) {
      setCountdownText('');
      return;
    }

    const update = () => {
      const diff = new Date(nextRace.start_time).getTime() - Date.now();
      if (diff <= 0) {
        setCountdownText('Started');
        return;
      }
      const totalSec = Math.floor(diff / 1000);
      const mins = Math.floor(totalSec / 60);
      const secs = totalSec % 60;
      setCountdownText(`${mins}m ${secs}s until jump`);
    };

    update();
    const interval = setInterval(update, 1000);
    return () => clearInterval(interval);
  }, [nextRace]);

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

  const handleGetTipNow = () => {
    if (nextRace) {
      setSelectedRace(nextRace);
      setSelectedBetType('best_bet');
      analytics.track('race_selected', { race_id: nextRace.id, racing_type: nextRace.racing_type });
      router.push('/tip-builder');
    } else {
      analytics.track('browse_races_clicked');
      router.push('/race-picker');
    }
  };

  const handleScheduleTip = () => {
    analytics.track('schedule_tip_clicked');
    router.push('/race-picker?mode=schedule');
  };

  const handleDeleteRecentTip = (savedTip: any) => {
    Alert.alert(
      'Delete Saved Tip',
      `Remove "${savedTip.tip?.recommended_bet || 'this tip'}" from your saved tips?`,
      [
        { text: 'Keep', style: 'cancel' },
        {
          text: 'Delete',
          style: 'destructive',
          onPress: async () => {
            setDeletingTipId(savedTip.id);
            try {
              await deleteSavedTip(savedTip.id);
              await clearTipCache();
              const tips = await getSavedTips().catch(() => []);
              setRecentTips(tips.slice(0, 5));
            } catch (error) {
              Alert.alert('Error', 'Failed to delete tip');
            } finally {
              setDeletingTipId(null);
            }
          },
        },
      ]
    );
  };

  const handleRacePress = (race: Race) => {
    analytics.track('race_selected', { race_id: race.id, racing_type: race.racing_type });
    router.push(`/race/${race.id}`);
  };

  if (loading || pendingPrefs) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={theme.primary} />
          <Text style={styles.loadingText}>
            {pendingPrefs ? 'Applying preferences...' : 'Loading races...'}
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>Horse Racing</Text>
            <Text style={styles.title}>Tips</Text>
          </View>
          <TouchableOpacity style={styles.notificationButton}>
            <Ionicons name="notifications-outline" size={24} color={theme.text} />
          </TouchableOpacity>
        </View>

        {/* Primary Action Card - Smart CTA */}
        <TouchableOpacity onPress={handleGetTipNow} activeOpacity={0.9}>
          <Animated.View
            style={[
              styles.primaryCard,
              isUrgent && styles.primaryCardUrgent,
              isUrgent && { opacity: pulseAnim },
            ]}
          >
            <View style={styles.primaryCardContent}>
              {isUrgent ? (
                <>
                  <View style={styles.urgentHeader}>
                    <Ionicons name="alert-circle" size={28} color="#fff" />
                    <Text style={styles.primaryCardTitle}>STARTING SOON</Text>
                  </View>
                  <Text style={styles.primaryCardSubtitle}>{countdownText}</Text>
                </>
              ) : (
                <>
                  <Ionicons name="flash" size={32} color="#fff" />
                  <Text style={styles.primaryCardTitle}>
                    {nextRace ? 'Get Tip Now' : "Browse Today's Races"}
                  </Text>
                  <Text style={styles.primaryCardSubtitle}>
                    {noRaceSoon ? "Browse Today's Races" : 'Instant recommendation for the next race'}
                  </Text>
                </>
              )}
            </View>
            {nextRace && !isUrgent && (
              <View style={styles.primaryCardBadge}>
                <Text style={styles.primaryCardBadgeText}>
                  {nextRace.track} R{nextRace.race_number} • {formatCountdown(nextRace.start_time)}
                </Text>
              </View>
            )}
          </Animated.View>
        </TouchableOpacity>

        {/* Secondary Action - Schedule */}
        <TouchableOpacity style={styles.secondaryCard} onPress={handleScheduleTip}>
          <Ionicons name="alarm-outline" size={24} color={theme.text} />
          <View style={styles.secondaryCardContent}>
            <Text style={styles.secondaryCardTitle}>Schedule a Tip</Text>
            <Text style={styles.secondaryCardSubtitle}>Get notified before your chosen race</Text>
          </View>
          <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
        </TouchableOpacity>

        {/* Next Up Section */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>
              Next Up{filtersActive ? '' : ''}
            </Text>
            <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
              {filtersActive && (
                <View
                  style={[
                    styles.filterBadge,
                    { backgroundColor: theme.primary + '20' },
                  ]}
                >
                  <Text
                    style={[
                      styles.filterBadgeText,
                      { color: theme.primary },
                    ]}
                  >
                    Filtered
                  </Text>
                </View>
              )}
              <TouchableOpacity onPress={() => router.push('/(tabs)/races')}>
                <Text style={styles.seeAllText}>See all</Text>
              </TouchableOpacity>
            </View>
          </View>

          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.horizontalList}
          >
            {upcomingRaces.slice(0, 5).map((race) => (
              <View key={race.id} style={styles.horizontalCard}>
                <RaceCard race={race} onPress={() => handleRacePress(race)} compact />
              </View>
            ))}
          </ScrollView>
        </View>

        {/* Recent Tips Section */}
        {recentTips.length > 0 && (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionTitle}>Recent Tips</Text>
              <TouchableOpacity>
                <Text style={styles.seeAllText}>View history</Text>
              </TouchableOpacity>
            </View>

            {recentTips.map((savedTip) => (
              <View key={savedTip.id} style={styles.recentTipCard}>
                <View style={styles.recentTipHeader}>
                  <View style={styles.recentTipInfo}>
                    <Text style={styles.recentTipBet}>{savedTip.tip?.recommended_bet || 'Tip'}</Text>
                    <Text style={styles.recentTipTime}>
                      {savedTip.tip?.race_info?.track || 'Track'}
                    </Text>
                  </View>
                  <TouchableOpacity
                    style={styles.recentTipDelete}
                    onPress={() => handleDeleteRecentTip(savedTip)}
                    disabled={deletingTipId === savedTip.id}
                  >
                    {deletingTipId === savedTip.id ? (
                      <ActivityIndicator size="small" color={theme.danger} />
                    ) : (
                      <Ionicons name="trash-outline" size={18} color={theme.danger} />
                    )}
                  </TouchableOpacity>
                </View>
              </View>
            ))}
          </View>
        )}

        {/* Empty state for recent tips */}
        {recentTips.length === 0 && (
          <View style={styles.emptyState}>
            <Ionicons name="bookmark-outline" size={40} color={theme.textTertiary} />
            <Text style={styles.emptyStateTitle}>No saved tips yet</Text>
            <Text style={styles.emptyStateSubtitle}>Your saved tips will appear here</Text>
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}