import React, { useState, useEffect, useMemo } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Switch,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import {
  getPreferences,
  updatePreferences,
  getTracksGrouped,
  getRaceOptions,
  getSavedTips,
  deleteSavedTip,
  clearTipCache,
} from '../../src/services/api';
import { UserPreferences, RaceOptions } from '../../src/types';
import { getBetTypeName } from '../../src/utils/formatters';
import { SearchableDropdown } from '../../src/components';
import { useTheme, Theme } from '../../src/theme/ThemeContext';
import { useAuthStore } from '../../src/store/authStore';
import { useScreenTracking } from '../../src/analytics/useAnalytics';

const createStyles = (theme: Theme) =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: theme.background,
    },
    loadingContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
    },
    header: {
      paddingHorizontal: 20,
      paddingTop: 8,
      paddingBottom: 16,
    },
    title: {
      fontSize: 32,
      fontWeight: '800',
      color: theme.text,
    },
    scrollView: {
      flex: 1,
    },
    scrollContent: {
      paddingBottom: 40,
    },
    section: {
      marginBottom: 24,
    },
    sectionTitle: {
      fontSize: 14,
      fontWeight: '600',
      color: theme.textSecondary,
      textTransform: 'uppercase',
      letterSpacing: 0.5,
      paddingHorizontal: 20,
      marginBottom: 8,
    },
    sectionSubtitle: {
      fontSize: 13,
      color: theme.textTertiary,
      paddingHorizontal: 20,
      marginBottom: 12,
    },
    profileCard: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: theme.card,
      marginHorizontal: 20,
      padding: 16,
      borderRadius: 16,
      gap: 16,
    },
    avatar: {
      width: 56,
      height: 56,
      borderRadius: 28,
      backgroundColor: theme.primary,
      alignItems: 'center',
      justifyContent: 'center',
    },
    profileInfo: {
      flex: 1,
    },
    profileName: {
      fontSize: 18,
      fontWeight: '700',
      color: theme.text,
    },
    profileEmail: {
      fontSize: 14,
      color: theme.textSecondary,
      marginTop: 2,
    },
    card: {
      backgroundColor: theme.card,
      marginHorizontal: 20,
      borderRadius: 16,
      overflow: 'hidden',
    },
    settingRow: {
      flexDirection: 'row',
      alignItems: 'center',
      padding: 16,
      gap: 14,
    },
    expandableRow: {
      flexDirection: 'row',
      alignItems: 'center',
      padding: 16,
      gap: 14,
    },
    settingIcon: {
      width: 36,
      height: 36,
      borderRadius: 10,
      backgroundColor: theme.borderLight,
      alignItems: 'center',
      justifyContent: 'center',
    },
    settingContent: {
      flex: 1,
    },
    settingLabel: {
      fontSize: 16,
      fontWeight: '600',
      color: theme.text,
    },
    settingDescription: {
      fontSize: 13,
      color: theme.textTertiary,
      marginTop: 2,
    },
    settingValue: {
      fontSize: 14,
      color: theme.textSecondary,
      marginTop: 2,
    },
    divider: {
      height: 1,
      backgroundColor: theme.borderLight,
      marginLeft: 66,
    },
    expandedContent: {
      paddingHorizontal: 16,
      paddingBottom: 16,
    },
    expandedHint: {
      fontSize: 12,
      color: theme.textTertiary,
      marginBottom: 12,
      marginLeft: 50,
    },
    chipGrid: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: 8,
      marginLeft: 50,
    },
    chip: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 6,
      paddingHorizontal: 14,
      paddingVertical: 10,
      borderRadius: 20,
      backgroundColor: theme.chipBg,
      borderWidth: 1,
      borderColor: theme.border,
    },
    chipWide: {
      width: '100%',
      justifyContent: 'space-between',
      borderRadius: 12,
      paddingVertical: 12,
    },
    chipActive: {
      backgroundColor: theme.chipActiveBg,
      borderColor: theme.chipActiveBg,
    },
    chipText: {
      fontSize: 14,
      fontWeight: '500',
      color: theme.chipText,
    },
    chipTextActive: {
      color: theme.chipActiveText,
    },
    chipDescription: {
      fontSize: 12,
      color: theme.textTertiary,
      marginTop: 2,
    },
    chipDescriptionActive: {
      color: theme.chipActiveText,
    },
    tracksContainer: {
      paddingHorizontal: 20,
      gap: 10,
    },
    trackChip: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 6,
      paddingHorizontal: 16,
      paddingVertical: 10,
      borderRadius: 20,
      backgroundColor: theme.card,
      borderWidth: 1,
      borderColor: theme.border,
      marginRight: 8,
    },
    trackChipActive: {
      backgroundColor: theme.chipActiveBg,
      borderColor: theme.chipActiveBg,
    },
    trackChipText: {
      fontSize: 14,
      fontWeight: '500',
      color: theme.chipText,
    },
    trackChipTextActive: {
      color: theme.chipActiveText,
    },
    trackDropdownContainer: {
      marginHorizontal: 20,
    },
    racingTypesContainer: {
      marginHorizontal: 20,
      marginBottom: 16,
    },
    racingTypesLabel: {
      fontSize: 14,
      fontWeight: '600',
      color: theme.chipText,
      marginBottom: 12,
    },
    racingTypesRow: {
      flexDirection: 'row',
      gap: 12,
    },
    racingTypeCard: {
      flex: 1,
      backgroundColor: theme.card,
      borderRadius: 16,
      padding: 16,
      alignItems: 'center',
      gap: 8,
      borderWidth: 2,
      borderColor: theme.border,
      position: 'relative',
    },
    racingTypeCardText: {
      fontSize: 13,
      fontWeight: '600',
      color: theme.textSecondary,
    },
    racingTypeCheck: {
      position: 'absolute',
      top: 8,
      right: 8,
      width: 18,
      height: 18,
      borderRadius: 9,
      alignItems: 'center',
      justifyContent: 'center',
    },
    racingTypesHint: {
      fontSize: 12,
      color: theme.textTertiary,
      marginTop: 10,
      textAlign: 'center',
    },
    versionText: {
      textAlign: 'center',
      fontSize: 13,
      color: theme.textTertiary,
      marginTop: 16,
      marginBottom: 20,
    },
    // Saved tips section
    emptyTipsContainer: {
      alignItems: 'center',
      padding: 32,
      gap: 8,
    },
    emptyTipsText: {
      fontSize: 16,
      fontWeight: '600',
      color: theme.textSecondary,
    },
    emptyTipsSubtext: {
      fontSize: 14,
      color: theme.textTertiary,
      textAlign: 'center',
      maxWidth: 260,
      lineHeight: 20,
    },
    savedTipRow: {
      flexDirection: 'row',
      alignItems: 'center',
      padding: 16,
      gap: 12,
    },
    savedTipContent: {
      flex: 1,
    },
    savedTipBet: {
      fontSize: 15,
      fontWeight: '600',
      color: theme.text,
    },
    savedTipMeta: {
      fontSize: 13,
      color: theme.textTertiary,
      marginTop: 2,
    },
    deleteTipButton: {
      width: 36,
      height: 36,
      borderRadius: 10,
      backgroundColor: theme.borderLight,
      alignItems: 'center',
      justifyContent: 'center',
    },
  });

export default function ProfileScreen() {
  const { theme, isDark, toggleTheme } = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const { user, isAuthenticated, logout } = useAuthStore();

  useScreenTracking('profile');

  const [preferences, setPreferences] = useState<UserPreferences | null>(null);
  const [tracks, setTracks] = useState<string[]>([]);
  const [tracksByType, setTracksByType] = useState<{ [key: string]: string[] }>({});
  const [raceOptions, setRaceOptions] = useState<RaceOptions | null>(null);
  const [loading, setLoading] = useState(true);
  const [expandedSection, setExpandedSection] = useState<string | null>(null);
  const [savedTips, setSavedTips] = useState<any[]>([]);
  const [savedTipsLoading, setSavedTipsLoading] = useState(false);
  const [deletingTipId, setDeletingTipId] = useState<string | null>(null);

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

  const loadData = async () => {
    try {
      const [prefsData, tracksData, optionsData] = await Promise.all([
        getPreferences(),
        getTracksGrouped(),
        getRaceOptions(),
      ]);
      setPreferences(prefsData);
      setTracks(tracksData.all);
      setTracksByType(tracksData.byType);
      setRaceOptions(optionsData);
    } catch (error) {
      console.error('Error loading preferences:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadSavedTips = async () => {
    setSavedTipsLoading(true);
    try {
      const tips = await getSavedTips();
      setSavedTips(tips);
    } catch (error) {
      console.error('Error loading saved tips:', error);
    } finally {
      setSavedTipsLoading(false);
    }
  };

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

  const handleDeleteTip = (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();
              await loadSavedTips();
            } catch (error) {
              Alert.alert('Error', 'Failed to delete tip');
            } finally {
              setDeletingTipId(null);
            }
          },
        },
      ]
    );
  };

  const handleToggleChannel = async (channel: 'push' | 'sms' | 'email') => {
    if (!preferences) return;

    const newChannels = {
      ...preferences.notification_channels,
      [channel]: !preferences.notification_channels[channel],
    };

    try {
      const updated = await updatePreferences({ notification_channels: newChannels });
      setPreferences(updated);
    } catch (error) {
      Alert.alert('Error', 'Failed to update preferences');
    }
  };

  const handleToggleFavoriteTrack = async (track: string) => {
    if (!preferences) return;

    const currentFavorites = preferences.favorite_tracks || [];
    const newFavorites = currentFavorites.includes(track)
      ? currentFavorites.filter((t) => t !== track)
      : [...currentFavorites, track];

    try {
      const updated = await updatePreferences({ favorite_tracks: newFavorites });
      setPreferences(updated);
    } catch (error) {
      Alert.alert('Error', 'Failed to update preferences');
    }
  };

  const handleToggleRaceClass = async (raceClass: string) => {
    if (!preferences) return;

    const current = preferences.preferred_race_classes || [];
    const newClasses = current.includes(raceClass)
      ? current.filter((c) => c !== raceClass)
      : [...current, raceClass];

    try {
      const updated = await updatePreferences({ preferred_race_classes: newClasses });
      setPreferences(updated);
    } catch (error) {
      Alert.alert('Error', 'Failed to update preferences');
    }
  };

  const handleToggleDistance = async (distance: string) => {
    if (!preferences) return;

    const current = preferences.preferred_distances || [];
    const newDistances = current.includes(distance)
      ? current.filter((d) => d !== distance)
      : [...current, distance];

    try {
      const updated = await updatePreferences({ preferred_distances: newDistances });
      setPreferences(updated);
    } catch (error) {
      Alert.alert('Error', 'Failed to update preferences');
    }
  };

  const handleToggleCondition = async (condition: string) => {
    if (!preferences) return;

    const current = preferences.preferred_conditions || [];
    const newConditions = current.includes(condition)
      ? current.filter((c) => c !== condition)
      : [...current, condition];

    try {
      const updated = await updatePreferences({ preferred_conditions: newConditions });
      setPreferences(updated);
    } catch (error) {
      Alert.alert('Error', 'Failed to update preferences');
    }
  };

  const handleToggleRacingType = async (racingType: string) => {
    if (!preferences) return;

    const current = preferences.preferred_racing_types || [];
    const newTypes = current.includes(racingType)
      ? current.filter((t) => t !== racingType)
      : [...current, racingType];

    try {
      const updated = await updatePreferences({ preferred_racing_types: newTypes });
      setPreferences(updated);
    } catch (error) {
      Alert.alert('Error', 'Failed to update preferences');
    }
  };

  const toggleSection = (section: string) => {
    setExpandedSection(expandedSection === section ? null : section);
  };

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={theme.primary} />
        </View>
      </SafeAreaView>
    );
  }

  const getSelectedCount = (items: string[] | undefined) => {
    if (!items || items.length === 0) return 'All';
    return `${items.length} selected`;
  };

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <View style={styles.header}>
        <Text style={styles.title}>Profile</Text>
      </View>

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Profile Section */}
        <View style={styles.section}>
          {isAuthenticated && user ? (
            <View style={styles.profileCard}>
              <View style={styles.avatar}>
                <Ionicons name="person" size={32} color={theme.primaryText} />
              </View>
              <View style={styles.profileInfo}>
                <Text style={styles.profileName}>{user.name || 'Racing Fan'}</Text>
                <Text style={styles.profileEmail}>{user.email}</Text>
              </View>
            </View>
          ) : (
            <TouchableOpacity
              style={styles.profileCard}
              onPress={() => router.push('/login')}
              activeOpacity={0.7}
            >
              <View style={[styles.avatar, { backgroundColor: theme.borderLight }]}>
                <Ionicons name="person-outline" size={32} color={theme.textTertiary} />
              </View>
              <View style={styles.profileInfo}>
                <Text style={styles.profileName}>Guest</Text>
                <Text style={styles.profileEmail}>Sign in to personalise your experience</Text>
              </View>
              <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
            </TouchableOpacity>
          )}
        </View>

        {/* Appearance Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Appearance</Text>

          <View style={styles.card}>
            <View style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons
                  name={isDark ? 'moon' : 'sunny'}
                  size={20}
                  color={isDark ? '#fbbf24' : '#111827'}
                />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Dark Mode</Text>
                <Text style={styles.settingDescription}>
                  {isDark ? 'Dark theme active' : 'Light theme active'}
                </Text>
              </View>
              <Switch
                value={isDark}
                onValueChange={toggleTheme}
                trackColor={{ false: theme.border, true: theme.primary }}
                thumbColor={isDark ? theme.primaryText : '#fff'}
              />
            </View>
          </View>
        </View>

        {/* Saved Tips Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Saved Tips</Text>
          <Text style={styles.sectionSubtitle}>
            Tips you have bookmarked for quick reference
          </Text>

          {savedTipsLoading && (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="small" color={theme.primary} />
            </View>
          )}

          {!savedTipsLoading && savedTips.length === 0 && (
            <View style={styles.emptyTipsContainer}>
              <Ionicons name="bookmark-outline" size={32} color={theme.textTertiary} />
              <Text style={styles.emptyTipsText}>No saved tips yet</Text>
              <Text style={styles.emptyTipsSubtext}>
                Save tips from race recommendations to view them here
              </Text>
            </View>
          )}

          {!savedTipsLoading && savedTips.length > 0 && (
            <View style={styles.card}>
              {savedTips.map((savedTip, index) => (
                <View key={savedTip.id}>
                  {index > 0 && <View style={styles.divider} />}
                  <View style={styles.savedTipRow}>
                    <View style={styles.savedTipContent}>
                      <Text style={styles.savedTipBet} numberOfLines={1}>
                        {savedTip.tip?.recommended_bet || 'Tip'}
                      </Text>
                      <Text style={styles.savedTipMeta}>
                        {savedTip.tip?.race_info?.track || 'Track'}
                        {savedTip.tip?.race_info?.race_number
                          ? ` • Race ${savedTip.tip.race_info.race_number}`
                          : ''}
                      </Text>
                    </View>
                    <TouchableOpacity
                      style={styles.deleteTipButton}
                      onPress={() => handleDeleteTip(savedTip)}
                      disabled={deletingTipId === savedTip.id}
                    >
                      {deletingTipId === savedTip.id ? (
                        <ActivityIndicator size="small" color={theme.danger} />
                      ) : (
                        <Ionicons name="trash-outline" size={20} color={theme.danger} />
                      )}
                    </TouchableOpacity>
                  </View>
                </View>
              ))}
            </View>
          )}
        </View>

        {/* Race Preferences Section */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Race Preferences</Text>
          <Text style={styles.sectionSubtitle}>
            Filter races shown in &ldquo;Next Up&rdquo; and recommendations
          </Text>

          {/* Racing Types - Always visible */}
          <View style={styles.racingTypesContainer}>
            <Text style={styles.racingTypesLabel}>Racing Types</Text>
            <View style={styles.racingTypesRow}>
              {raceOptions?.racing_types?.map((type) => {
                const isSelected =
                  !preferences?.preferred_racing_types?.length ||
                  preferences?.preferred_racing_types?.includes(type.id);
                const iconName =
                  type.id === 'thoroughbred'
                    ? 'ribbon'
                    : type.id === 'harness'
                      ? 'car-sport'
                      : 'paw';
                const colors = {
                  thoroughbred: '#3b82f6',
                  harness: '#8b5cf6',
                  greyhound: '#22c55e',
                };
                const color = colors[type.id as keyof typeof colors] || theme.textSecondary;

                return (
                  <TouchableOpacity
                    key={type.id}
                    style={[
                      styles.racingTypeCard,
                      isSelected && { borderColor: color, backgroundColor: color + '20' },
                    ]}
                    onPress={() => handleToggleRacingType(type.id)}
                  >
                    <Ionicons
                      name={iconName as any}
                      size={28}
                      color={isSelected ? color : theme.textTertiary}
                    />
                    <Text style={[styles.racingTypeCardText, isSelected && { color }]}>
                      {type.name}
                    </Text>
                    {isSelected && (
                      <View style={[styles.racingTypeCheck, { backgroundColor: color }]}>
                        <Ionicons name="checkmark" size={12} color="#fff" />
                      </View>
                    )}
                  </TouchableOpacity>
                );
              })}
            </View>
            <Text style={styles.racingTypesHint}>
              {!preferences?.preferred_racing_types?.length
                ? 'Showing all racing types'
                : `Showing ${preferences.preferred_racing_types.length} type(s)`}
            </Text>
          </View>

          <View style={styles.card}>
            {/* Race Classes */}
            <TouchableOpacity style={styles.expandableRow} onPress={() => toggleSection('classes')}>
              <View style={styles.settingIcon}>
                <Ionicons name="trophy" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Race Classes</Text>
                <Text style={styles.settingValue}>
                  {getSelectedCount(preferences?.preferred_race_classes)}
                </Text>
              </View>
              <Ionicons
                name={expandedSection === 'classes' ? 'chevron-up' : 'chevron-down'}
                size={20}
                color={theme.textTertiary}
              />
            </TouchableOpacity>

            {expandedSection === 'classes' && raceOptions && (
              <View style={styles.expandedContent}>
                <Text style={styles.expandedHint}>Leave empty to show all race classes</Text>
                <View style={styles.chipGrid}>
                  {raceOptions.race_classes.map((option) => {
                    const isSelected = preferences?.preferred_race_classes?.includes(option.id);
                    return (
                      <TouchableOpacity
                        key={option.id}
                        style={[styles.chip, isSelected && styles.chipActive]}
                        onPress={() => handleToggleRaceClass(option.id)}
                      >
                        <Text style={[styles.chipText, isSelected && styles.chipTextActive]}>
                          {option.name}
                        </Text>
                        {isSelected && <Ionicons name="checkmark" size={14} color={theme.chipActiveText} />}
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
            )}

            <View style={styles.divider} />

            {/* Distances */}
            <TouchableOpacity
              style={styles.expandableRow}
              onPress={() => toggleSection('distances')}
            >
              <View style={styles.settingIcon}>
                <Ionicons name="speedometer" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Distance Preferences</Text>
                <Text style={styles.settingValue}>
                  {getSelectedCount(preferences?.preferred_distances)}
                </Text>
              </View>
              <Ionicons
                name={expandedSection === 'distances' ? 'chevron-up' : 'chevron-down'}
                size={20}
                color={theme.textTertiary}
              />
            </TouchableOpacity>

            {expandedSection === 'distances' && raceOptions && (
              <View style={styles.expandedContent}>
                <View style={styles.chipGrid}>
                  {raceOptions.distances.map((option) => {
                    const isSelected = preferences?.preferred_distances?.includes(option.id);
                    return (
                      <TouchableOpacity
                        key={option.id}
                        style={[styles.chip, styles.chipWide, isSelected && styles.chipActive]}
                        onPress={() => handleToggleDistance(option.id)}
                      >
                        <View>
                          <Text style={[styles.chipText, isSelected && styles.chipTextActive]}>
                            {option.name}
                          </Text>
                          <Text
                            style={[
                              styles.chipDescription,
                              isSelected && styles.chipDescriptionActive,
                            ]}
                          >
                            {option.description}
                          </Text>
                        </View>
                        {isSelected && <Ionicons name="checkmark" size={14} color={theme.chipActiveText} />}
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
            )}

            <View style={styles.divider} />

            {/* Track Conditions */}
            <TouchableOpacity
              style={styles.expandableRow}
              onPress={() => toggleSection('conditions')}
            >
              <View style={styles.settingIcon}>
                <Ionicons name="cloudy" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Track Conditions</Text>
                <Text style={styles.settingValue}>
                  {getSelectedCount(preferences?.preferred_conditions)}
                </Text>
              </View>
              <Ionicons
                name={expandedSection === 'conditions' ? 'chevron-up' : 'chevron-down'}
                size={20}
                color={theme.textTertiary}
              />
            </TouchableOpacity>

            {expandedSection === 'conditions' && raceOptions && (
              <View style={styles.expandedContent}>
                <View style={styles.chipGrid}>
                  {raceOptions.conditions.map((option) => {
                    const isSelected = preferences?.preferred_conditions?.includes(option.id);
                    return (
                      <TouchableOpacity
                        key={option.id}
                        style={[styles.chip, isSelected && styles.chipActive]}
                        onPress={() => handleToggleCondition(option.id)}
                      >
                        <Text style={[styles.chipText, isSelected && styles.chipTextActive]}>
                          {option.name}
                        </Text>
                        {isSelected && <Ionicons name="checkmark" size={14} color={theme.chipActiveText} />}
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
            )}
          </View>
        </View>

        {/* Favorite Tracks */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Favorite Tracks</Text>
          <Text style={styles.sectionSubtitle}>Select tracks to prioritize in your feed</Text>

          <View style={styles.trackDropdownContainer}>
            <SearchableDropdown
              placeholder="Search tracks..."
              items={tracks || []}
              selectedItems={preferences?.favorite_tracks || []}
              onSelectionChange={async (selected) => {
                try {
                  const updated = await updatePreferences({ favorite_tracks: selected });
                  setPreferences(updated);
                } catch (error) {
                  Alert.alert('Error', 'Failed to update favorite tracks');
                }
              }}
              multiSelect={true}
              groupedItems={tracksByType}
            />
          </View>
        </View>

        {/* Notification Channels */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Notification Channels</Text>

          <View style={styles.card}>
            <View style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons name="notifications" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Push Notifications</Text>
                <Text style={styles.settingDescription}>Receive tips in-app</Text>
              </View>
              <Switch
                value={preferences?.notification_channels?.push ?? true}
                onValueChange={() => handleToggleChannel('push')}
                trackColor={{ false: theme.border, true: theme.primary }}
                thumbColor="#fff"
              />
            </View>

            <View style={styles.divider} />

            <View style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons name="chatbubble" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>SMS</Text>
                <Text style={styles.settingDescription}>Coming soon</Text>
              </View>
              <Switch
                value={preferences?.notification_channels?.sms ?? false}
                onValueChange={() => handleToggleChannel('sms')}
                trackColor={{ false: theme.border, true: theme.primary }}
                thumbColor="#fff"
                disabled
              />
            </View>

            <View style={styles.divider} />

            <View style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons name="mail" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Email</Text>
                <Text style={styles.settingDescription}>Coming soon</Text>
              </View>
              <Switch
                value={preferences?.notification_channels?.email ?? false}
                onValueChange={() => handleToggleChannel('email')}
                trackColor={{ false: theme.border, true: theme.primary }}
                thumbColor="#fff"
                disabled
              />
            </View>
          </View>
        </View>

        {/* Default Settings */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Defaults</Text>

          <View style={styles.card}>
            <View style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons name="flash" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Default Bet Type</Text>
                <Text style={styles.settingValue}>
                  {getBetTypeName(preferences?.default_bet_type || 'best_bet')}
                </Text>
              </View>
              <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
            </View>

            <View style={styles.divider} />

            <View style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons name="time" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Default Lead Time</Text>
                <Text style={styles.settingValue}>
                  {preferences?.default_lead_time || 15} minutes before
                </Text>
              </View>
              <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
            </View>
          </View>
        </View>

        {/* Support */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Support</Text>

          <View style={styles.card}>
            <TouchableOpacity style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons name="help-circle" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Help Center</Text>
              </View>
              <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
            </TouchableOpacity>

            <View style={styles.divider} />

            <TouchableOpacity style={styles.settingRow}>
              <View style={styles.settingIcon}>
                <Ionicons name="document-text" size={20} color={theme.text} />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Terms & Privacy</Text>
              </View>
              <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
            </TouchableOpacity>

            <View style={styles.divider} />

            <TouchableOpacity style={styles.settingRow}>
              <View style={[styles.settingIcon, { backgroundColor: '#fef2f2' }]}>
                <Ionicons name="warning" size={20} color="#dc2626" />
              </View>
              <View style={styles.settingContent}>
                <Text style={styles.settingLabel}>Responsible Gambling</Text>
                <Text style={styles.settingDescription}>Set limits & get help</Text>
              </View>
              <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
            </TouchableOpacity>

            {isAuthenticated && (
              <>
                <View style={styles.divider} />
                <TouchableOpacity
                  style={styles.settingRow}
                  onPress={() =>
                    Alert.alert('Log Out', 'Are you sure you want to log out?', [
                      { text: 'Cancel', style: 'cancel' },
                      {
                        text: 'Log Out',
                        style: 'destructive',
                        onPress: async () => {
                          await logout();
                          router.replace('/login');
                        },
                      },
                    ])
                  }
                >
                  <View style={[styles.settingIcon, { backgroundColor: '#fef2f2' }]}>
                    <Ionicons name="log-out" size={20} color="#dc2626" />
                  </View>
                  <View style={styles.settingContent}>
                    <Text style={[styles.settingLabel, { color: '#dc2626' }]}>Log Out</Text>
                    <Text style={styles.settingDescription}>Sign out of your account</Text>
                  </View>
                  <Ionicons name="chevron-forward" size={20} color={theme.textTertiary} />
                </TouchableOpacity>
              </>
            )}
          </View>
        </View>

        {/* Version */}
        <Text style={styles.versionText}>Version 1.0.0</Text>
      </ScrollView>
    </SafeAreaView>
  );
}