import React, { useCallback, useEffect, useState } from 'react';
import { StyleSheet, View, Text, FlatList, Animated, Dimensions } from 'react-native';
import { colors } from '@/constants/colors';
import { Trade } from '@/types';
import { ArrowUp, ArrowDown, Clock } from 'lucide-react-native';
import { useTheme } from '@/context/ThemeContext';

interface ActiveTradesListProps {
  trades: Trade[];
}

export default function ActiveTradesList({ trades }: ActiveTradesListProps) {
  const { theme, colors } = useTheme();
  const [isListReady, setIsListReady] = useState(true); // Set to true by default to ensure visibility
  const fadeAnim = new Animated.Value(1); // Start with 1 to ensure visibility
  
  // Get screen dimensions for responsive layout
  const screenWidth = Dimensions.get('window').width;
  const isSmallScreen = screenWidth < 360;
  
  // Ensure trades is always an array
  const safeTradesArray = Array.isArray(trades) ? trades : [];
  
  if (!safeTradesArray.length) return null;
  
  const calculateTimeRemaining = useCallback((endTime: Date | string) => {
    const now = new Date();
    const end = typeof endTime === 'string' ? new Date(endTime) : endTime;
    const diff = Math.max(0, Math.floor((end.getTime() - now.getTime()) / 1000));
    
    const minutes = Math.floor(diff / 60);
    const seconds = diff % 60;
    
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  }, []);
  
  const renderTradeItem = useCallback(({ item }: { item: Trade }) => {
    if (!item) return null;
    
    const isUpTrade = item.tradeType === 'Buy Up';
    
    return (
      <View style={[
        styles.tradeItem,
        { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.3)' : 'rgba(0, 0, 0, 0.1)' }
      ]}>
        <View style={styles.tradeTypeContainer}>
          {isUpTrade ? (
            <ArrowUp size={isSmallScreen ? 14 : 16} color={colors.success} />
          ) : (
            <ArrowDown size={isSmallScreen ? 14 : 16} color={colors.error} />
          )}
          <Text style={[
            styles.tradeType,
            isUpTrade ? styles.upTradeText : styles.downTradeText,
            { fontSize: isSmallScreen ? 10 : 12 }
          ]}>
            {item.tradeType}
          </Text>
        </View>
        
        <View style={styles.tradeDetails}>
          <Text style={[
            styles.tradeAmount, 
            { 
              color: colors.text,
              fontSize: isSmallScreen ? 11 : 13
            }
          ]}>
            {item.investmentAmount.toLocaleString()} BATZ
          </Text>
          <Text style={[
            styles.tradePrice, 
            { 
              color: colors.textSecondary,
              fontSize: isSmallScreen ? 10 : 12
            }
          ]}>
            @ {item.buyPrice.toFixed(2)}
          </Text>
        </View>
        
        <View style={[
          styles.timeContainer,
          { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.1)' }
        ]}>
          <Clock size={isSmallScreen ? 12 : 14} color={colors.textSecondary} />
          <Text style={[
            styles.timeRemaining, 
            { 
              color: colors.textSecondary,
              fontSize: isSmallScreen ? 10 : 12
            }
          ]}>
            {calculateTimeRemaining(item.endTime)}
          </Text>
        </View>
      </View>
    );
  }, [theme, colors, calculateTimeRemaining, isSmallScreen]);
  
  const keyExtractor = useCallback((item: Trade) => item?.tradeId || Math.random().toString(), []);
  
  // Calculate item width based on screen size
  const getItemWidth = () => {
    if (isSmallScreen) return 130;
    return 150;
  };
  
  return (
    <View 
      style={[
        styles.container, 
        { 
          backgroundColor: theme === 'dark' ? colors.bgDark : colors.backgroundSecondary,
          zIndex: 2,
          padding: isSmallScreen ? 8 : 12,
        }
      ]}
    >
      <Text style={[
        styles.title, 
        { 
          color: colors.text,
          fontSize: isSmallScreen ? 12 : 14,
          marginBottom: isSmallScreen ? 6 : 8
        }
      ]}>
        Active Trades
      </Text>
      <FlatList
        data={safeTradesArray}
        renderItem={renderTradeItem}
        keyExtractor={keyExtractor}
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={[
          styles.listContent,
          { paddingVertical: isSmallScreen ? 2 : 4 }
        ]}
        scrollEventThrottle={16}
        decelerationRate="fast"
        snapToAlignment="start"
        snapToInterval={getItemWidth() + 10} // Width of item + margin
        removeClippedSubviews={false} // Set to false to ensure visibility
        maxToRenderPerBatch={10}
        windowSize={5}
        initialNumToRender={5}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    borderRadius: 12,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  title: {
    fontWeight: 'bold',
  },
  listContent: {
    paddingHorizontal: 2,
  },
  tradeItem: {
    borderRadius: 8,
    padding: 8,
    marginRight: 8,
    width: 150,
    borderWidth: 1,
    borderColor: colors.borderGray,
  },
  tradeTypeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 4,
  },
  tradeType: {
    fontWeight: 'bold',
    marginLeft: 4,
  },
  upTradeText: {
    color: colors.success,
  },
  downTradeText: {
    color: colors.error,
  },
  tradeDetails: {
    marginBottom: 4,
  },
  tradeAmount: {
    fontWeight: '600',
  },
  tradePrice: {
    fontSize: 12,
  },
  timeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 3,
    paddingHorizontal: 5,
    borderRadius: 4,
    alignSelf: 'flex-start',
  },
  timeRemaining: {
    marginLeft: 4,
  },
});