import React, { useEffect, useRef, useState } from 'react';
import { StyleSheet, View, Text, Dimensions, Platform, Animated, TouchableOpacity, Image, AppState, PanResponder } from 'react-native';
import { LineChart } from 'react-native-chart-kit';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { useTheme } from '@/context/ThemeContext';
import { LinearGradient } from 'expo-linear-gradient';
import { ChevronUp, ChevronDown, ChevronDown as ChevronDownIcon, Info, ZoomIn, ZoomOut, AlertCircle } from 'lucide-react-native';
import MarketSelectionModal from './MarketSelectionModal';

interface TradeChartProps {
  marketName: string;
}

export default function TradeChart({ marketName }: TradeChartProps) {
  // Get screen dimensions for responsive layout
  const screenWidth = Dimensions.get('window').width;
  const screenHeight = Dimensions.get('window').height;
  const isSmallScreen = screenWidth < 360;
  const isLargeScreen = screenWidth > 480;
  const isShortScreen = screenHeight < 700;
  
  // Get store values at the top level
  const { 
    markets, 
    activeTrades, 
    currentMarketForTrade,
    setCurrentMarketForTrade,
    updateMarketPrice,
    lastMarketUpdateTimestamp,
    isUserFromNigeria,
    userCurrency,
    loadChartDataFromStorage,
    saveChartDataToStorage,
    simulateBackgroundUpdates
  } = useTradeStore();
  
  const { theme, colors } = useTheme();
  
  // State declarations at the top level
  const [chartWidth, setChartWidth] = useState(screenWidth - (isSmallScreen ? 16 : 24));
  const [chartHeight, setChartHeight] = useState(isShortScreen ? 160 : 180);
  const [timerValue, setTimerValue] = useState<number | null>(null);
  const [selectedTimeframe, setSelectedTimeframe] = useState('1m');
  const [showMarketModal, setShowMarketModal] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [appState, setAppState] = useState(AppState.currentState);
  const [lastUpdateTime, setLastUpdateTime] = useState(Date.now());
  const [showTooltip, setShowTooltip] = useState(false);
  const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
  const [tooltipValue, setTooltipValue] = useState('');
  const [tooltipIndex, setTooltipIndex] = useState(-1);
  const [chartZoom, setChartZoom] = useState(1);
  const [showHelp, setShowHelp] = useState(false);
  const [isChartReady, setIsChartReady] = useState(true); // Set to true by default to ensure visibility
  const [isChartDataLoaded, setIsChartDataLoaded] = useState(false);
  
  // Refs
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const fadeAnim = useRef(new Animated.Value(1)).current;
  const slideAnim = useRef(new Animated.Value(0)).current;
  const chartUpdateIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const chartRef = useRef(null);
  const backgroundTimeRef = useRef<number | null>(null);
  
  // Animation refs for blinking effect
  const blinkAnim = useRef(new Animated.Value(0.4)).current;
  const pulseAnim = useRef(new Animated.Value(1)).current;
  
  // Ensure activeTrades is always an array
  const safeActiveTrades = Array.isArray(activeTrades) ? activeTrades : [];
  
  // Find active trade for this market
  const activeTrade = safeActiveTrades.find(trade => trade?.market === marketName);
  
  // Currency symbol based on user location
  const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
  
  // Load chart data from storage on mount
  useEffect(() => {
    const loadData = async () => {
      try {
        if (!isChartDataLoaded) {
          await loadChartDataFromStorage();
          setIsChartDataLoaded(true);
        }
      } catch (error) {
        console.error("Error loading chart data:", error);
        setError("Failed to load chart data. Please refresh.");
      }
    };
    
    loadData();
  }, [isChartDataLoaded, loadChartDataFromStorage]);
  
  // Start blinking animation for trade line header
  useEffect(() => {
    if (activeTrade) {
      // Create a repeating blink animation
      const createBlinkAnimation = () => {
        Animated.sequence([
          Animated.timing(blinkAnim, {
            toValue: 1,
            duration: 800,
            useNativeDriver: true,
          }),
          Animated.timing(blinkAnim, {
            toValue: 0.4,
            duration: 800,
            useNativeDriver: true,
          })
        ]).start(() => {
          // Repeat the animation
          createBlinkAnimation();
        });
      };
      
      // Create a repeating pulse animation
      const createPulseAnimation = () => {
        Animated.sequence([
          Animated.timing(pulseAnim, {
            toValue: 1.1,
            duration: 1000,
            useNativeDriver: true,
          }),
          Animated.timing(pulseAnim, {
            toValue: 1,
            duration: 1000,
            useNativeDriver: true,
          })
        ]).start(() => {
          // Repeat the animation
          createPulseAnimation();
        });
      };
      
      // Start both animations
      createBlinkAnimation();
      createPulseAnimation();
      
      // Clean up animations on unmount
      return () => {
        blinkAnim.stopAnimation();
        pulseAnim.stopAnimation();
      };
    }
  }, [activeTrade]);
  
  // Pan responder for chart interactions
  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant: (evt, gestureState) => {
        // Handle touch start
        const { locationX, locationY } = evt.nativeEvent;
        handleChartTouch(locationX, locationY);
      },
      onPanResponderMove: (evt, gestureState) => {
        // Handle touch move
        const { locationX, locationY } = evt.nativeEvent;
        handleChartTouch(locationX, locationY);
      },
      onPanResponderRelease: () => {
        // Hide tooltip when touch ends
        setTimeout(() => {
          setShowTooltip(false);
        }, 2000);
      },
    })
  ).current;
  
  // Handle app state changes for background processing
  useEffect(() => {
    // Setup app state change listener for background processing
    const subscription = AppState.addEventListener('change', nextAppState => {
      if (appState === 'active' && nextAppState.match(/inactive|background/)) {
        // App is going to background
        backgroundTimeRef.current = Date.now();
        
        // Save chart data to storage when app goes to background
        saveChartDataToStorage().catch(err => {
          console.error("Error saving chart data when going to background:", err);
        });
      } else if (appState.match(/inactive|background/) && nextAppState === 'active') {
        // App is coming back to foreground
        if (backgroundTimeRef.current) {
          const timeInBackground = Date.now() - backgroundTimeRef.current;
          
          // If app was in background for more than 2 seconds
          if (timeInBackground > 2000) {
            // Simulate the missed updates
            simulateBackgroundUpdates(timeInBackground);
            setLastUpdateTime(Date.now());
          }
          
          backgroundTimeRef.current = null;
        }
      }
      
      setAppState(nextAppState);
    });
    
    return () => {
      subscription.remove();
      if (chartUpdateIntervalRef.current) {
        clearInterval(chartUpdateIntervalRef.current);
      }
    };
  }, [appState, saveChartDataToStorage, simulateBackgroundUpdates]);
  
  // Setup continuous chart updates even when component is not focused
  useEffect(() => {
    const market = markets[marketName];
    if (!market) return;
    
    // Set up an interval to update the chart
    chartUpdateIntervalRef.current = setInterval(() => {
      try {
        // Only update if we're in the foreground or if it's been a while
        if (appState === 'active' || Date.now() - lastUpdateTime > 10000) {
          setLastUpdateTime(Date.now());
          
          // Get active trade for this market to apply bias
          const activeTrade = safeActiveTrades.find(t => t?.market === marketName);
          const tradeType = activeTrade ? activeTrade.tradeType : null;
          
          // Generate a biased price movement
          const volatility = 0.03; // 3% volatility
          let bias = 0;
          
          if (tradeType) {
            // If user is in a Buy Up trade, slightly bias downward (negative)
            // If user is in a Buy Down trade, slightly bias upward (positive)
            bias = tradeType === 'Buy Up' ? -0.01 : 0.01;
          } else {
            // When no active trade, add some random trend reversals
            bias = Math.random() > 0.7 ? 0.02 : -0.02;
          }
          
          const randomFactor = Math.random() - 0.5;
          const change = market.currentPrice * (volatility * randomFactor + bias);
          const newPrice = Math.max(1, market.currentPrice + change);
          
          updateMarketPrice(marketName, newPrice);
        }
      } catch (error) {
        console.error("Error updating chart in background:", error);
      }
    }, market.updateInterval);
    
    return () => {
      if (chartUpdateIntervalRef.current) {
        clearInterval(chartUpdateIntervalRef.current);
        chartUpdateIntervalRef.current = null;
      }
    };
  }, [markets, marketName, appState, lastUpdateTime, safeActiveTrades, updateMarketPrice]);
  
  // Save chart data to storage periodically
  useEffect(() => {
    // Save chart data every 30 seconds
    const saveInterval = setInterval(() => {
      if (appState === 'active') {
        saveChartDataToStorage().catch(err => {
          console.error("Error saving chart data in periodic save:", err);
        });
      }
    }, 30000); // 30 seconds
    
    return () => {
      clearInterval(saveInterval);
    };
  }, [appState, saveChartDataToStorage]);
  
  useEffect(() => {
    if (activeTrade) {
      try {
        // Start timer
        const endTime = typeof activeTrade.endTime === 'string' 
          ? new Date(activeTrade.endTime).getTime() 
          : activeTrade.endTime.getTime();
        
        const updateTimer = () => {
          const now = Date.now();
          const remaining = Math.max(0, Math.ceil((endTime - now) / 1000));
          setTimerValue(remaining);
          
          if (remaining <= 0) {
            if (timerRef.current) {
              clearInterval(timerRef.current);
              timerRef.current = null;
            }
            setTimerValue(null);
          }
        };
        
        updateTimer();
        timerRef.current = setInterval(updateTimer, 1000);
        
        return () => {
          if (timerRef.current) {
            clearInterval(timerRef.current);
            timerRef.current = null;
          }
        };
      } catch (error) {
        console.error("Error setting up trade timer:", error);
        setError("Failed to track trade time. Please refresh.");
      }
    } else {
      setTimerValue(null);
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    }
  }, [activeTrade]);
  
  // Handle layout changes
  const onLayout = (event: any) => {
    try {
      const { width, height } = event.nativeEvent.layout;
      setChartWidth(width - 16);
      
      // Adjust chart height based on available space
      if (height && height > 100) {
        const newHeight = isShortScreen ? Math.min(160, height - 40) : Math.min(180, height - 40);
        setChartHeight(newHeight);
      }
    } catch (error) {
      console.error("Error in onLayout:", error);
    }
  };
  
  // Handle market modal
  const handleOpenMarketModal = () => {
    try {
      setShowMarketModal(true);
    } catch (error) {
      console.error("Error opening market modal:", error);
      setError("Failed to open market selection. Please try again.");
    }
  };
  
  // Handle chart touch for tooltip
  const handleChartTouch = (x: number, y: number) => {
    try {
      const market = markets[marketName];
      if (!market) return;
      
      // Calculate which data point was touched
      const dataPointWidth = chartWidth / (market.chartDataPoints.length - 1);
      const index = Math.round(x / dataPointWidth);
      
      if (index >= 0 && index < market.chartDataPoints.length) {
        const value = market.chartDataPoints[index];
        setTooltipValue(value.toFixed(2));
        setTooltipPosition({ x, y });
        setTooltipIndex(index);
        setShowTooltip(true);
      }
    } catch (error) {
      console.error("Error handling chart touch:", error);
    }
  };
  
  // Handle chart zoom
  const handleZoomIn = () => {
    setChartZoom(prev => Math.min(prev + 0.25, 2));
  };
  
  const handleZoomOut = () => {
    setChartZoom(prev => Math.max(prev - 0.25, 0.5));
  };
  
  // Toggle help tooltip
  const toggleHelp = () => {
    setShowHelp(!showHelp);
  };
  
  if (!markets[marketName]) {
    console.error("Market not found:", marketName);
    return (
      <View style={[styles.errorContainer, { backgroundColor: colors.backgroundSecondary }]}>
        <Text style={[styles.errorText, { color: colors.error }]}>Market data not available</Text>
      </View>
    );
  }
  
  const market = markets[marketName];
  
  // Calculate price change percentage
  const lastPrice = market.chartDataPoints[market.chartDataPoints.length - 1];
  const prevPrice = market.chartDataPoints[market.chartDataPoints.length - 2] || lastPrice;
  const priceChange = lastPrice - prevPrice;
  const priceChangePercent = (priceChange / prevPrice) * 100;
  const isPriceUp = priceChange >= 0;
  
  // Calculate visible data points based on zoom
  const visibleDataPoints = () => {
    const allDataPoints = [...market.chartDataPoints];
    if (chartZoom === 1) return allDataPoints;
    
    const dataLength = allDataPoints.length;
    const visibleCount = Math.floor(dataLength / chartZoom);
    return allDataPoints.slice(dataLength - visibleCount);
  };
  
  return (
    <View 
      style={[
        styles.container, 
        { 
          backgroundColor: colors.backgroundSecondary,
          paddingHorizontal: isSmallScreen ? 8 : 12,
          paddingVertical: isSmallScreen ? 4 : 6,
          marginHorizontal: isSmallScreen ? 4 : 6,
          zIndex: 2,
        }
      ]} 
      onLayout={onLayout}
    >
      {error && (
        <View style={[styles.errorContainer, { backgroundColor: theme === 'dark' ? 'rgba(231, 76, 60, 0.1)' : 'rgba(231, 76, 60, 0.05)' }]}>
          <Text style={[styles.errorText, { color: colors.error }]}>{error}</Text>
          <TouchableOpacity 
            style={[styles.retryButton, { backgroundColor: colors.error }]}
            onPress={() => setError(null)}
          >
            <Text style={styles.retryButtonText}>Dismiss</Text>
          </TouchableOpacity>
        </View>
      )}
      
      <View style={styles.chartHeader}>
        <TouchableOpacity 
          style={styles.marketInfo}
          onPress={handleOpenMarketModal}
          activeOpacity={0.7}
        >
          <View style={styles.marketNameContainer}>
            <Image 
              source={{ uri: market.iconUrl }}
              style={[
                styles.marketIcon,
                { width: isSmallScreen ? 14 : 16,
                  height: isSmallScreen ? 14 : 16,
                  opacity: isChartDataLoaded ? 1 : 0.5 // Show loading state
                }
              ]}
              resizeMode="contain"
            />
            <Text style={[
              styles.marketName, 
              { 
                color: colors.text,
                fontSize: isSmallScreen ? 14 : 16
              }
            ]}>
              {market.displayName}
            </Text>
            <ChevronDownIcon 
              size={isSmallScreen ? 12 : 14} 
              color={colors.textSecondary} 
            />
          </View>
          <View style={styles.priceContainer}>
            <Text style={[
              styles.currentPrice, 
              { 
                color: colors.text,
                fontSize: isSmallScreen ? 12 : 14
              }
            ]}>
              {market.currentPrice.toFixed(2)} {currencySymbol}
            </Text>
            <View style={[styles.changeContainer, isPriceUp ? styles.priceUp : styles.priceDown]}>
              {isPriceUp ? 
                <ChevronUp size={isSmallScreen ? 10 : 12} color={colors.success} /> : 
                <ChevronDown size={isSmallScreen ? 10 : 12} color={colors.error} />
              }
              <Text style={[
                styles.priceChange, 
                isPriceUp ? styles.priceUpText : styles.priceDownText,
                { fontSize: isSmallScreen ? 9 : 10 }
              ]}>
                {Math.abs(priceChangePercent).toFixed(2)}%
              </Text>
            </View>
          </View>
        </TouchableOpacity>
        <View style={[
          styles.timeframeContainer, 
          { 
            backgroundColor: theme === 'dark' ? colors.bgDark : colors.backgroundSecondary,
            padding: isSmallScreen ? 1 : 2
          }
        ]}>
          <TouchableOpacity onPress={() => setSelectedTimeframe('1m')}>
            <Text style={[
              styles.timeframeButton, 
              selectedTimeframe === '1m' && styles.activeTimeframe,
              { 
                color: selectedTimeframe === '1m' ? colors.textWhite : colors.textSecondary,
                fontSize: isSmallScreen ? 9 : 10,
                paddingHorizontal: isSmallScreen ? 4 : 6
              }
            ]}>1m</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setSelectedTimeframe('5m')}>
            <Text style={[
              styles.timeframeButton, 
              selectedTimeframe === '5m' && styles.activeTimeframe,
              { 
                color: selectedTimeframe === '5m' ? colors.textWhite : colors.textSecondary,
                fontSize: isSmallScreen ? 9 : 10,
                paddingHorizontal: isSmallScreen ? 4 : 6
              }
            ]}>5m</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setSelectedTimeframe('15m')}>
            <Text style={[
              styles.timeframeButton, 
              selectedTimeframe === '15m' && styles.activeTimeframe,
              { 
                color: selectedTimeframe === '15m' ? colors.textWhite : colors.textSecondary,
                fontSize: isSmallScreen ? 9 : 10,
                paddingHorizontal: isSmallScreen ? 4 : 6
              }
            ]}>15m</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => setSelectedTimeframe('1h')}>
            <Text style={[
              styles.timeframeButton, 
              selectedTimeframe === '1h' && styles.activeTimeframe,
              { 
                color: selectedTimeframe === '1h' ? colors.textWhite : colors.textSecondary,
                fontSize: isSmallScreen ? 9 : 10,
                paddingHorizontal: isSmallScreen ? 4 : 6
              }
            ]}>1h</Text>
          </TouchableOpacity>
        </View>
      </View>
      
      <View style={[
        styles.chartContainer, 
        { 
          backgroundColor: theme === 'dark' ? colors.bgBlack : colors.backgroundSecondary,
          height: chartHeight + 30, // Add extra space for timer and controls
          zIndex: 2,
        }
      ]}>
        <Image 
          source={{ uri: 'https://cdn.prod.website-files.com/66b7dcae754fe5eef2139e69/67d2bd08bfc05787cd4dc601_THE%20BATZ%20Trade%20logo.png' }}
          style={[styles.backgroundImage, { opacity: theme === 'dark' ? 0.05 : 0.02 }]}
          resizeMode="contain"
        />
        
        {/* Chart Controls */}
        <View style={styles.chartControls}>
          <TouchableOpacity 
            style={[
              styles.chartControlButton, 
              { 
                backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.5)' : 'rgba(0, 0, 0, 0.2)',
                width: isSmallScreen ? 20 : 24,
                height: isSmallScreen ? 20 : 24,
              }
            ]}
            onPress={handleZoomIn}
          >
            <ZoomIn 
              size={isSmallScreen ? 12 : 14} 
              color={theme === 'dark' ? colors.textWhite : colors.text} 
            />
          </TouchableOpacity>
          <TouchableOpacity 
            style={[
              styles.chartControlButton, 
              { 
                backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.5)' : 'rgba(0, 0, 0, 0.2)',
                width: isSmallScreen ? 20 : 24,
                height: isSmallScreen ? 20 : 24,
              }
            ]}
            onPress={handleZoomOut}
          >
            <ZoomOut 
              size={isSmallScreen ? 12 : 14} 
              color={theme === 'dark' ? colors.textWhite : colors.text} 
            />
          </TouchableOpacity>
        </View>
        
        {/* Chart Help Button */}
        <TouchableOpacity 
          style={[
            styles.chartHelpButton, 
            { 
              backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.5)' : 'rgba(0, 0, 0, 0.2)',
              width: isSmallScreen ? 20 : 24,
              height: isSmallScreen ? 20 : 24,
            }
          ]}
          onPress={toggleHelp}
        >
          <Info 
            size={isSmallScreen ? 12 : 14} 
            color={theme === 'dark' ? colors.textWhite : colors.text} 
          />
        </TouchableOpacity>
        
        {/* Help Tooltip */}
        {showHelp && (
          <View style={[
            styles.helpTooltip,
            { 
              backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.7)',
              width: isSmallScreen ? '90%' : '80%',
              top: isSmallScreen ? 30 : 35,
            }
          ]}>
            <View style={styles.helpHeader}>
              <AlertCircle size={isSmallScreen ? 12 : 14} color={colors.primary} />
              <Text style={[
                styles.helpTitle,
                { fontSize: isSmallScreen ? 11 : 12 }
              ]}>
                Chart Help
              </Text>
              <TouchableOpacity onPress={toggleHelp}>
                <Text style={styles.helpClose}>×</Text>
              </TouchableOpacity>
            </View>
            <Text style={[
              styles.helpText,
              { fontSize: isSmallScreen ? 9 : 10 }
            ]}>
              • Touch and hold on the chart to see price values
            </Text>
            <Text style={[
              styles.helpText,
              { fontSize: isSmallScreen ? 9 : 10 }
            ]}>
              • Use zoom buttons to adjust chart view
            </Text>
            {activeTrade && (
              <Text style={[
                styles.helpText,
                { fontSize: isSmallScreen ? 9 : 10 }
              ]}>
                • Blinking line shows your active trade position
              </Text>
            )}
          </View>
        )}
        
        <View 
          ref={chartRef}
          {...panResponder.panHandlers}
          style={[styles.chartWrapper, { zIndex: 3 }]}
        >
          <LineChart
            data={{
              labels: market.chartLabels,
              datasets: [
                {
                  data: visibleDataPoints(),
                  color: () => isPriceUp ? colors.success : colors.error,
                  strokeWidth: isSmallScreen ? 1.5 : 2
                }
              ]
            }}
            width={chartWidth}
            height={chartHeight}
            chartConfig={{
              backgroundColor: 'transparent',
              backgroundGradientFrom: 'transparent',
              backgroundGradientTo: 'transparent',
              decimalPlaces: 2,
              color: () => isPriceUp ? colors.success : colors.error,
              labelColor: () => colors.textSecondary,
              style: {
                borderRadius: 16
              },
              propsForDots: {
                r: '0',
              },
              fillShadowGradientFrom: isPriceUp ? colors.success : colors.error,
              fillShadowGradientTo: 'transparent',
              fillShadowGradientOpacity: 0.3,
              // Adjust font size for small screens
              propsForLabels: {
                fontSize: isSmallScreen ? 7 : 8,
              }
            }}
            bezier
            style={styles.chart}
            withDots={false}
            withInnerLines={false}
            withOuterLines={true}
            withVerticalLines={false}
            withHorizontalLines={true}
            withVerticalLabels={false}
            withHorizontalLabels={true}
          />
          
          {/* Price Tooltip */}
          {showTooltip && (
            <View 
              style={[
                styles.tooltip, 
                { 
                  left: tooltipPosition.x - 40,
                  top: tooltipPosition.y - 40,
                  backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.7)',
                  padding: isSmallScreen ? 4 : 6,
                }
              ]}
            >
              <Text style={[
                styles.tooltipText,
                { fontSize: isSmallScreen ? 9 : 10 }
              ]}>
                {tooltipValue} {currencySymbol}
              </Text>
              <View style={[
                styles.tooltipArrow,
                { borderTopColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.7)' }
              ]} />
            </View>
          )}
        </View>
        
        {activeTrade && (
          <View style={[
            styles.tradeLine,
            activeTrade.tradeType === 'Buy Up' ? styles.buyUpLine : styles.buyDownLine,
            { zIndex: 4 }
          ]}>
            <LinearGradient
              colors={[
                activeTrade.tradeType === 'Buy Up' ? 'rgba(46, 204, 113, 0.3)' : 'rgba(231, 76, 60, 0.3)',
                activeTrade.tradeType === 'Buy Up' ? 'rgba(46, 204, 113, 0.1)' : 'rgba(231, 76, 60, 0.1)',
                'transparent'
              ]}
              style={styles.tradeLineGradient}
            />
            
            {/* Blinking Trade Line Header */}
            <Animated.View 
              style={[
                styles.tradeLineContent, 
                { 
                  backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.7)' : 'rgba(0, 0, 0, 0.5)',
                  opacity: blinkAnim,
                  transform: [{ scale: pulseAnim }],
                  paddingHorizontal: isSmallScreen ? 4 : 6,
                  paddingVertical: isSmallScreen ? 2 : 3,
                }
              ]}
            >
              <Text style={[
                styles.tradeLineText,
                activeTrade.tradeType === 'Buy Up' ? styles.buyUpText : styles.buyDownText,
                { fontSize: isSmallScreen ? 9 : 10 }
              ]}>
                {activeTrade.tradeType} @ {activeTrade.buyPrice.toFixed(2)} {currencySymbol}
              </Text>
              {activeTrade.tradeType === 'Buy Up' ? 
                <ChevronUp size={isSmallScreen ? 10 : 12} color={colors.success} /> : 
                <ChevronDown size={isSmallScreen ? 10 : 12} color={colors.error} />
              }
            </Animated.View>
            
            {/* Trade Line Marker */}
            <View style={[
              styles.tradeLineMarker,
              { 
                backgroundColor: activeTrade.tradeType === 'Buy Up' ? colors.success : colors.error,
                width: isSmallScreen ? 3 : 4,
              }
            ]} />
          </View>
        )}
        
        {timerValue !== null && activeTrade && (
          <View style={[
            styles.timerContainer,
            {
              height: isSmallScreen ? 6 : 8,
              bottom: isSmallScreen ? 4 : 6,
              zIndex: 5,
            }
          ]}>
            <View style={[
              styles.timerFill, 
              { 
                width: `${(timerValue / (activeTrade ? 
                  (new Date(activeTrade.endTime).getTime() - new Date(activeTrade.startTime).getTime()) / 1000 : 60)) * 100}%`,
                backgroundColor: activeTrade?.tradeType === 'Buy Up' ? colors.success : colors.error
              }
            ]} />
            <Text style={[
              styles.timerText, 
              { 
                color: theme === 'dark' ? colors.textWhite : colors.text,
                fontSize: isSmallScreen ? 9 : 10,
                bottom: isSmallScreen ? 12 : 14,
              }
            ]}>
              {timerValue}s
            </Text>
          </View>
        )}
      </View>
      
      <View style={styles.volumeContainer}>
        <View style={[
          styles.volumeBar, 
          { 
            backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)',
            height: isSmallScreen ? 2 : 3,
          }
        ]}>
          <View 
            style={[
              styles.volumeFill, 
              { width: `${Math.random() * 100}%`, backgroundColor: isPriceUp ? colors.success : colors.error }
            ]} 
          />
        </View>
        <Text style={[
          styles.volumeText, 
          { 
            color: colors.textSecondary,
            fontSize: isSmallScreen ? 8 : 9,
          }
        ]}>
          Volume: {Math.floor(Math.random() * 10000) + 5000}
        </Text>
      </View>
      
      {/* Market Selection Modal */}
      <MarketSelectionModal 
        visible={showMarketModal}
        onClose={() => setShowMarketModal(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    borderRadius: 12,
    marginVertical: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 6,
    elevation: 4,
    position: 'relative',
  },
  chartHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
    zIndex: 3,
  },
  marketInfo: {
    flexDirection: 'column',
  },
  marketNameContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  marketIcon: {
    marginRight: 4,
  },
  marketName: {
    fontWeight: 'bold',
    marginBottom: 2,
    marginRight: 4,
  },
  priceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  currentPrice: {
    fontWeight: '600',
    marginRight: 6,
  },
  changeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 4,
    paddingVertical: 1,
    borderRadius: 4,
  },
  priceChange: {
    fontWeight: '500',
  },
  priceUp: {
    color: colors.success,
    backgroundColor: 'rgba(46, 204, 113, 0.1)',
  },
  priceDown: {
    color: colors.error,
    backgroundColor: 'rgba(231, 76, 60, 0.1)',
  },
  priceUpText: {
    color: colors.success,
  },
  priceDownText: {
    color: colors.error,
  },
  timeframeContainer: {
    flexDirection: 'row',
    borderRadius: 6,
    zIndex: 3,
  },
  timeframeButton: {
    paddingHorizontal: 6,
    paddingVertical: 3,
    borderRadius: 4,
  },
  activeTimeframe: {
    backgroundColor: colors.secondary,
    fontWeight: '500',
  },
  chartContainer: {
    position: 'relative',
    borderRadius: 10,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 3,
    elevation: 3,
  },
  backgroundImage: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    zIndex: 1,
  },
  chartWrapper: {
    position: 'relative',
  },
  chart: {
    borderRadius: 10,
    paddingRight: 0,
    paddingLeft: 0,
  },
  chartControls: {
    position: 'absolute',
    top: 6,
    right: 6,
    zIndex: 5,
    flexDirection: 'row',
  },
  chartControlButton: {
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 4,
  },
  chartHelpButton: {
    position: 'absolute',
    top: 6,
    left: 6,
    zIndex: 5,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  helpTooltip: {
    position: 'absolute',
    left: 6,
    padding: 8,
    borderRadius: 8,
    zIndex: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
  },
  helpHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 6,
  },
  helpTitle: {
    color: '#FFFFFF',
    fontWeight: 'bold',
    marginLeft: 6,
    flex: 1,
  },
  helpClose: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: 'bold',
  },
  helpText: {
    color: '#FFFFFF',
    marginBottom: 3,
  },
  tooltip: {
    position: 'absolute',
    borderRadius: 6,
    zIndex: 10,
  },
  tooltipText: {
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  tooltipArrow: {
    position: 'absolute',
    bottom: -8,
    left: '50%',
    marginLeft: -4,
    borderLeftWidth: 4,
    borderRightWidth: 4,
    borderTopWidth: 8,
    borderStyle: 'solid',
    backgroundColor: 'transparent',
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent',
  },
  tradeLine: {
    position: 'absolute',
    right: 0,
    top: '50%',
    width: '100%',
    height: 30,
    justifyContent: 'center',
  },
  tradeLineGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: 30,
  },
  tradeLineContent: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'absolute',
    right: 8,
    borderRadius: 4,
  },
  tradeLineText: {
    color: colors.textWhite,
    marginRight: 2,
  },
  buyUpText: {
    color: colors.success,
  },
  buyDownText: {
    color: colors.error,
  },
  buyUpLine: {
    borderTopWidth: 1,
    borderTopColor: colors.success,
  },
  buyDownLine: {
    borderTopWidth: 1,
    borderTopColor: colors.error,
  },
  tradeLineMarker: {
    position: 'absolute',
    left: 0,
    height: 30,
    borderTopRightRadius: 2,
    borderBottomRightRadius: 2,
  },
  timerContainer: {
    position: 'absolute',
    left: '5%',
    width: '90%',
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    borderRadius: 30,
    overflow: 'hidden',
  },
  timerFill: {
    height: '100%',
    borderRadius: 30,
  },
  timerText: {
    position: 'absolute',
    width: '100%',
    textAlign: 'center',
    fontWeight: 'bold',
  },
  volumeContainer: {
    marginTop: 4,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  volumeBar: {
    flex: 1,
    borderRadius: 2,
    marginRight: 6,
    overflow: 'hidden',
  },
  volumeFill: {
    height: '100%',
    borderRadius: 2,
  },
  volumeText: {
    textAlign: 'right',
  },
  errorContainer: {
    padding: 8,
    borderRadius: 8,
    marginBottom: 8,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  errorText: {
    color: colors.error,
    fontSize: 11,
    flex: 1,
  },
  retryButton: {
    paddingVertical: 3,
    paddingHorizontal: 6,
    borderRadius: 4,
  },
  retryButtonText: {
    color: colors.textWhite,
    fontSize: 10,
    fontWeight: 'bold',
  },
});