import React, { useState, useEffect, useRef, useCallback } from 'react';
import { StyleSheet, View, Text, FlatList, TouchableOpacity, Animated, Dimensions, Platform } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { LinearGradient } from 'expo-linear-gradient';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { useTheme } from '@/context/ThemeContext';
import TradeHistoryItem from '@/components/TradeHistoryItem';
import { Filter, ArrowUpDown, Clock, Check, X, ChevronDown } from 'lucide-react-native';
import { useFocusEffect } from 'expo-router';

export default function TradeHistoryScreen() {
  // Get store values at the top level
  const { 
    isDemoAccount, 
    demoTradeHistory, 
    tradeHistory, 
    markTradeHistoryAsViewed,
    isUserFromNigeria,
    hasNewTrades
  } = useTradeStore();
  
  const { theme, colors } = useTheme();
  
  // State declarations at the top level
  const [activeTab, setActiveTab] = useState('all');
  const [sortOrder, setSortOrder] = useState('newest');
  const [showFilterOptions, setShowFilterOptions] = useState(false);
  const [filteredHistory, setFilteredHistory] = useState([]);
  const [isScrolling, setIsScrolling] = useState(false);
  
  // Animation values
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;
  const filterMenuAnim = useRef(new Animated.Value(0)).current;
  
  // Get current trade history based on account mode
  const currentTradeHistory = isDemoAccount ? demoTradeHistory : tradeHistory;
  
  // Mark trade history as viewed when screen is focused
  useFocusEffect(
    React.useCallback(() => {
      try {
        if (hasNewTrades) {
          markTradeHistoryAsViewed();
        }
      } catch (error) {
        console.error("Error marking trade history as viewed:", error);
      }
      
      return () => {
        // Cleanup if needed
      };
    }, [hasNewTrades])
  );
  
  // Animate screen on mount
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 800,
        useNativeDriver: true,
      }),
    ]).start();
    
    // Cleanup animations on unmount
    return () => {
      fadeAnim.stopAnimation();
      slideAnim.stopAnimation();
      filterMenuAnim.stopAnimation();
    };
  }, []);
  
  // Filter and sort trade history when dependencies change
  useEffect(() => {
    try {
      if (!currentTradeHistory || !Array.isArray(currentTradeHistory)) {
        setFilteredHistory([]);
        return;
      }
      
      let filtered = [...currentTradeHistory];
      
      // Apply filter
      if (activeTab !== 'all') {
        filtered = filtered.filter(trade => trade.status === activeTab);
      }
      
      // Apply sort
      filtered.sort((a, b) => {
        try {
          const dateA = new Date(a.timestamp).getTime();
          const dateB = new Date(b.timestamp).getTime();
          return sortOrder === 'newest' ? dateB - dateA : dateA - dateB;
        } catch (error) {
          console.error("Error sorting trades:", error);
          return 0;
        }
      });
      
      setFilteredHistory(filtered);
    } catch (error) {
      console.error("Error filtering trade history:", error);
      setFilteredHistory([]);
    }
  }, [currentTradeHistory, activeTab, sortOrder]);
  
  // Toggle filter options menu
  const toggleFilterOptions = () => {
    try {
      if (showFilterOptions) {
        Animated.timing(filterMenuAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: false,
        }).start(() => setShowFilterOptions(false));
      } else {
        setShowFilterOptions(true);
        Animated.timing(filterMenuAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: false,
        }).start();
      }
    } catch (error) {
      console.error("Error toggling filter options:", error);
    }
  };
  
  // Calculate stats
  const totalTrades = Array.isArray(currentTradeHistory) ? currentTradeHistory.length : 0;
  const winningTrades = Array.isArray(currentTradeHistory) ? 
    currentTradeHistory.filter(trade => trade.status === 'win').length : 0;
  const losingTrades = Array.isArray(currentTradeHistory) ? 
    currentTradeHistory.filter(trade => trade.status === 'loss').length : 0;
  const winRate = totalTrades > 0 ? Math.round((winningTrades / totalTrades) * 100) : 0;
  
  // Calculate total profit/loss
  const totalProfitLoss = Array.isArray(currentTradeHistory) ? 
    currentTradeHistory.reduce((sum, trade) => {
      // Only add positive profit to the total (wins)
      return sum + (trade.profitLoss > 0 ? trade.profitLoss : 0);
    }, 0) : 0;
  
  // Scroll event handlers
  const handleScrollBegin = useCallback(() => {
    setIsScrolling(true);
  }, []);
  
  const handleScrollEnd = useCallback(() => {
    setIsScrolling(false);
  }, []);
  
  // Render item with index for animation
  const renderItem = useCallback(({ item, index }) => (
    <TradeHistoryItem 
      trade={item} 
      index={index} 
    />
  ), []);
  
  // Keyextractor for FlatList
  const keyExtractor = useCallback((item) => item.id, []);
  
  // Empty component for FlatList
  const ListEmptyComponent = useCallback(() => (
    <View style={[
      styles.emptyContainer, 
      { backgroundColor: theme === 'light' ? colors.backgroundSecondary : undefined }
    ]}>
      <Text style={[styles.emptyText, { color: colors.text }]}>No trade history found</Text>
      <Text style={[styles.emptySubtext, { color: colors.textSecondary }]}>
        Your completed trades will appear here
      </Text>
    </View>
  ), [theme, colors]);
  
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={['bottom']}>
      {theme === 'dark' && (
        <LinearGradient
          colors={['rgba(30, 39, 46, 0.8)', 'rgba(0, 0, 0, 1)']}
          style={styles.backgroundGradient}
        />
      )}
      
      <Animated.View 
        style={[
          styles.content,
          { 
            opacity: fadeAnim,
            transform: [{ translateY: slideAnim }]
          }
        ]}
      >
        {/* Stats Section */}
        <View style={[styles.statsContainer, { backgroundColor: theme === 'light' ? colors.backgroundSecondary : undefined }]}>
          <View style={[styles.statCard, { backgroundColor: theme === 'light' ? colors.card : 'rgba(30, 39, 46, 0.5)' }]}>
            <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total Trades</Text>
            <Text style={[styles.statValue, { color: colors.text }]}>{totalTrades}</Text>
          </View>
          
          <View style={[styles.statCard, { backgroundColor: theme === 'light' ? colors.card : 'rgba(30, 39, 46, 0.5)' }]}>
            <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Win Rate</Text>
            <Text style={[
              styles.statValue,
              winRate > 50 ? styles.positiveValue : winRate < 50 ? styles.negativeValue : { color: colors.text }
            ]}>
              {winRate}%
            </Text>
          </View>
          
          <View style={[styles.statCard, { backgroundColor: theme === 'light' ? colors.card : 'rgba(30, 39, 46, 0.5)' }]}>
            <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total Profit</Text>
            <Text style={[
              styles.statValue,
              totalProfitLoss > 0 ? styles.positiveValue : totalProfitLoss < 0 ? styles.negativeValue : { color: colors.text }
            ]}>
              {totalProfitLoss.toFixed(2)} {isUserFromNigeria ? 'NGN' : 'USDT'}
            </Text>
          </View>
        </View>
        
        {/* Filter Controls */}
        <View style={styles.filterContainer}>
          <View style={[styles.tabsContainer, { backgroundColor: theme === 'light' ? colors.backgroundSecondary : 'rgba(30, 39, 46, 0.5)' }]}>
            <TouchableOpacity 
              style={[styles.tab, activeTab === 'all' && styles.activeTab]}
              onPress={() => setActiveTab('all')}
            >
              <Text style={[
                styles.tabText, 
                { color: activeTab === 'all' ? colors.primary : colors.textSecondary }
              ]}>All</Text>
            </TouchableOpacity>
            
            <TouchableOpacity 
              style={[styles.tab, activeTab === 'win' && styles.activeTab]}
              onPress={() => setActiveTab('win')}
            >
              <Check size={14} color={activeTab === 'win' ? colors.primary : colors.textSecondary} />
              <Text style={[
                styles.tabText, 
                { color: activeTab === 'win' ? colors.primary : colors.textSecondary }
              ]}>Wins</Text>
            </TouchableOpacity>
            
            <TouchableOpacity 
              style={[styles.tab, activeTab === 'loss' && styles.activeTab]}
              onPress={() => setActiveTab('loss')}
            >
              <X size={14} color={activeTab === 'loss' ? colors.primary : colors.textSecondary} />
              <Text style={[
                styles.tabText, 
                { color: activeTab === 'loss' ? colors.primary : colors.textSecondary }
              ]}>Losses</Text>
            </TouchableOpacity>
            
            <TouchableOpacity 
              style={[styles.tab, activeTab === 'active' && styles.activeTab]}
              onPress={() => setActiveTab('active')}
            >
              <Clock size={14} color={activeTab === 'active' ? colors.primary : colors.textSecondary} />
              <Text style={[
                styles.tabText, 
                { color: activeTab === 'active' ? colors.primary : colors.textSecondary }
              ]}>Active</Text>
            </TouchableOpacity>
          </View>
          
          <TouchableOpacity 
            style={[styles.filterButton, { backgroundColor: theme === 'light' ? colors.backgroundSecondary : 'rgba(30, 39, 46, 0.5)' }]}
            onPress={toggleFilterOptions}
          >
            <Filter size={18} color={colors.textSecondary} />
            <ChevronDown size={14} color={colors.textSecondary} />
          </TouchableOpacity>
        </View>
        
        {/* Filter Options Menu */}
        {showFilterOptions && (
          <Animated.View 
            style={[
              styles.filterOptionsMenu,
              {
                maxHeight: filterMenuAnim.interpolate({
                  inputRange: [0, 1],
                  outputRange: [0, 100]
                }),
                opacity: filterMenuAnim,
                backgroundColor: theme === 'light' ? colors.card : 'rgba(17, 17, 17, 0.9)'
              }
            ]}
          >
            <Text style={[styles.filterOptionsTitle, { color: colors.text }]}>Sort By:</Text>
            <View style={styles.sortOptions}>
              <TouchableOpacity 
                style={[
                  styles.sortOption, 
                  sortOrder === 'newest' && styles.activeSortOption,
                  { backgroundColor: theme === 'light' ? colors.backgroundSecondary : 'rgba(30, 39, 46, 0.5)' }
                ]}
                onPress={() => setSortOrder('newest')}
              >
                <Text style={[
                  styles.sortOptionText, 
                  { color: sortOrder === 'newest' ? colors.primary : colors.textSecondary }
                ]}>
                  Newest First
                </Text>
                {sortOrder === 'newest' && <Check size={14} color={colors.primary} />}
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={[
                  styles.sortOption, 
                  sortOrder === 'oldest' && styles.activeSortOption,
                  { backgroundColor: theme === 'light' ? colors.backgroundSecondary : 'rgba(30, 39, 46, 0.5)' }
                ]}
                onPress={() => setSortOrder('oldest')}
              >
                <Text style={[
                  styles.sortOptionText, 
                  { color: sortOrder === 'oldest' ? colors.primary : colors.textSecondary }
                ]}>
                  Oldest First
                </Text>
                {sortOrder === 'oldest' && <Check size={14} color={colors.primary} />}
              </TouchableOpacity>
            </View>
          </Animated.View>
        )}
        
        {/* Trade History List */}
        <FlatList
          data={filteredHistory}
          renderItem={renderItem}
          keyExtractor={keyExtractor}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
          ListEmptyComponent={ListEmptyComponent}
          scrollEventThrottle={16}
          onScrollBeginDrag={handleScrollBegin}
          onScrollEndDrag={handleScrollEnd}
          onMomentumScrollBegin={handleScrollBegin}
          onMomentumScrollEnd={handleScrollEnd}
          decelerationRate={Platform.OS === 'ios' ? 'normal' : 0.985}
          overScrollMode="never"
          bounces={false}
          bouncesZoom={false}
          removeClippedSubviews={Platform.OS !== 'web'}
          maxToRenderPerBatch={10}
          windowSize={10}
          updateCellsBatchingPeriod={50}
          initialNumToRender={10}
          keyboardShouldPersistTaps="handled"
          keyboardDismissMode="on-drag"
        />
      </Animated.View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  content: {
    flex: 1,
    paddingTop: 16,
  },
  statsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    marginBottom: 16,
  },
  statCard: {
    flex: 1,
    borderRadius: 10,
    padding: 12,
    marginHorizontal: 4,
    alignItems: 'center',
  },
  statLabel: {
    fontSize: 12,
    marginBottom: 4,
  },
  statValue: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  positiveValue: {
    color: colors.success,
  },
  negativeValue: {
    color: colors.error,
  },
  filterContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    marginBottom: 8,
  },
  tabsContainer: {
    flexDirection: 'row',
    borderRadius: 8,
    padding: 2,
  },
  tab: {
    paddingVertical: 6,
    paddingHorizontal: 10,
    borderRadius: 6,
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 2,
  },
  activeTab: {
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
  },
  tabText: {
    fontSize: 12,
    marginLeft: 4,
  },
  filterButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
    paddingHorizontal: 10,
    borderRadius: 8,
  },
  filterOptionsMenu: {
    marginHorizontal: 16,
    borderRadius: 8,
    padding: 12,
    marginBottom: 8,
    overflow: 'hidden',
  },
  filterOptionsTitle: {
    fontSize: 14,
    fontWeight: '500',
    marginBottom: 8,
  },
  sortOptions: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  sortOption: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
    paddingHorizontal: 10,
    borderRadius: 6,
    flex: 1,
    marginHorizontal: 4,
    justifyContent: 'space-between',
  },
  activeSortOption: {
    borderWidth: 1,
    borderColor: colors.primary,
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
  },
  sortOptionText: {
    fontSize: 12,
  },
  listContent: {
    paddingHorizontal: 16,
    paddingBottom: 16,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 40,
    borderRadius: 12,
    marginTop: 20,
  },
  emptyText: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  emptySubtext: {
    fontSize: 14,
    textAlign: 'center',
  },
});