import React, { useState, useEffect, useRef, useCallback } from 'react';
import { StyleSheet, View, ScrollView, Platform, Animated, Easing, AppState, Vibration, Dimensions, InteractionManager } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { useToast } from '@/context/ToastContext';
import { useLocalSearchParams, Stack } from 'expo-router';
import { useTheme } from '@/context/ThemeContext';
import AccountHeader from '@/components/AccountHeader';
import AccountTypeSwitch from '@/components/AccountTypeSwitch';
import HeaderDepositButton from '@/components/HeaderDepositButton';
import TradeChart from '@/components/TradeChart';
import TradeBuyBar from '@/components/TradeBuyBar';
import RefillButton from '@/components/RefillButton';
import BalanceModal from '@/components/BalanceModal';
import DepositModal from '@/components/DepositModal';
import RewardModal from '@/components/RewardModal';
import TutorialOverlay from '@/components/TutorialOverlay';
import ActiveTradesList from '@/components/ActiveTradesList';
import { Wallet, ChartLine, ArrowUpDown } from 'lucide-react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { useConnectionStatus } from '@/hooks/useConnectionStatus';
import { CONFIG } from '@/constants/config';

export default function TradeScreen() {
  // Add Stack.Screen to set the header title
  <Stack.Screen options={{ headerTitle: "Trade", headerShown: true }} />
  
  // Get screen dimensions for responsive layout
  const screenWidth = Dimensions.get('window').width;
  const screenHeight = Dimensions.get('window').height;
  const isSmallScreen = screenWidth < 360;
  const isMediumScreen = screenWidth >= 360 && screenWidth < 480;
  const isLargeScreen = screenWidth >= 480;
  const isShortScreen = screenHeight < 700;
  
  // Get URL params to check if we should open deposit modal or show tutorial
  const params = useLocalSearchParams();
  const openDepositModalParam = params.openDepositModal;
  const showTutorialParam = params.showTutorial;
  
  // Get store values at the top level
  const { 
    markets, 
    currentMarketForTrade, 
    updateMarketPrice,
    tradeCount,
    activeTrades,
    completeTrade,
    lastMarketUpdateTimestamp,
    selectedDepositMethod,
    isUserFromNigeria,
    userCountry,
    isDemoAccount,
    demoBalance,
    realBalance,
    loadChartDataFromStorage,
    saveChartDataToStorage,
    simulateBackgroundUpdates,
    updateAllMarketPrices,
    setLastUpdateTime
  } = useTradeStore();
  
  const { showToast } = useToast();
  const { theme, colors } = useTheme();
  const { isConnected, checkConnection } = useConnectionStatus();
  
  // State declarations at the top level
  const [showBalanceModal, setShowBalanceModal] = useState(false);
  const [showDepositModal, setShowDepositModal] = useState(false);
  const [showRewardModal, setShowRewardModal] = useState(false);
  const [showTutorial, setShowTutorial] = useState(false);
  const [tutorialChecked, setTutorialChecked] = useState(false);
  const [appState, setAppState] = useState(AppState.currentState);
  const [isScrolling, setIsScrolling] = useState(false);
  const [isContentReady, setIsContentReady] = useState(false);
  const [isChartDataLoaded, setIsChartDataLoaded] = useState(false);
  const [investment, setInvestment] = useState('');
  const [error, setError] = useState('');
  
  // Animation values
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;
  
  // References for tutorial - explicitly create refs for each target element
  const balanceRef = useRef(null);
  const chartRef = useRef(null);
  const controlsRef = useRef(null);
  const scrollViewRef = useRef(null);
  const backgroundTimeRef = useRef<number | null>(null);
  const backgroundUpdateIntervalRef = useRef<NodeJS.Timeout | null>(null);
  
  // Tutorial steps - improved with shorter, clearer content
  const tutorialSteps = [
    {
      targetRef: balanceRef,
      title: "Your Balance",
      message: "Shows your available coins for trading. Switch between Demo and Real accounts from the top right.",
      icon: <Wallet size={20} color={colors.primary} />
    },
    {
      targetRef: chartRef,
      title: "Price Chart",
      message: "Watch market movements here. Green shows price increases, red shows decreases. Use these patterns to predict future movements.",
      icon: <ChartLine size={20} color={colors.primary} />
    },
    {
      targetRef: controlsRef,
      title: "Trade Controls",
      message: "Enter investment amount, select duration, then predict if price will rise (Buy Up) or fall (Buy Down) within that time.",
      icon: <ArrowUpDown size={20} color={colors.primary} />
    }
  ];
  
  // Ensure activeTrades is always an array
  const safeActiveTrades = Array.isArray(activeTrades) ? activeTrades : [];
  
  // 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);
      }
    };
    
    loadData();
  }, [isChartDataLoaded, loadChartDataFromStorage]);
  
  // Check if we should open deposit modal from URL params
  useEffect(() => {
    if (openDepositModalParam === 'true') {
      // If in demo mode, show toast instead of opening modal
      if (isDemoAccount) {
        showToast(
          "Deposits are not available in Demo mode. Switch to Real Account to deposit funds.",
          "info"
        );
        return;
      }
      
      setShowDepositModal(true);
      
      // If we have a selected deposit method, show toast notification
      if (selectedDepositMethod) {
        showToast(`${selectedDepositMethod} selected for deposit`, 'info');
      }
    }
  }, [openDepositModalParam, selectedDepositMethod, isDemoAccount, showToast]);
  
  // Check if we should show tutorial from URL params
  useEffect(() => {
    if (showTutorialParam === 'true') {
      // Show tutorial regardless of whether it's been shown before
      // Small delay to ensure UI is ready
      setTimeout(() => {
        setShowTutorial(true);
        showToast("Trading guide ready", "info");
      }, 100);
    }
  }, [showTutorialParam, showToast]);
  
  // Animate screen on mount
  useEffect(() => {
    try {
      // Mark content as ready immediately to ensure it's visible
      setIsContentReady(true);
      
      // Delay animations slightly to ensure smooth initial render
      InteractionManager.runAfterInteractions(() => {
        Animated.parallel([
          Animated.timing(fadeAnim, {
            toValue: 1,
            duration: 500,
            useNativeDriver: true,
            easing: Easing.out(Easing.ease),
          }),
          Animated.timing(slideAnim, {
            toValue: 0,
            duration: 500,
            useNativeDriver: true,
            easing: Easing.out(Easing.ease),
          }),
        ]).start();
      });
    } catch (error) {
      console.error("Animation error:", error);
      // Ensure content is shown even if animation fails
      setIsContentReady(true);
    }
  }, [fadeAnim, slideAnim]);
  
  // Check if tutorial should be shown (first time user)
  useEffect(() => {
    const checkTutorial = async () => {
      try {
        // Skip if we're already showing the tutorial from URL params
        if (showTutorialParam === 'true') return;
        
        if (tutorialChecked) return; // Prevent multiple checks
        
        let tutorialShown = false;
        try {
          const value = await AsyncStorage.getItem('tutorialShown');
          tutorialShown = value === 'true';
        } catch (storageError) {
          console.error("Error reading from AsyncStorage:", storageError);
        }
        
        if (!tutorialShown) {
          // Delay tutorial to allow UI to render first
          setTimeout(() => {
            setShowTutorial(true);
          }, 1000);
        }
        
        setTutorialChecked(true);
      } catch (error) {
        console.error("Error checking tutorial status:", error);
        setTutorialChecked(true); // Mark as checked even on error to prevent loops
      }
    };
    
    checkTutorial();
  }, [tutorialChecked, showTutorialParam]);
  
  // Handle tutorial completion
  const handleTutorialComplete = async () => {
    try {
      setShowTutorial(false);
      
      // Provide haptic feedback on native platforms
      if (Platform.OS !== 'web') {
        try {
          Vibration.vibrate(20);
        } catch (error) {
          console.error("Vibration error:", error);
        }
      }
      
      try {
        await AsyncStorage.setItem('tutorialShown', 'true');
      } catch (storageError) {
        console.error("Error saving to AsyncStorage:", storageError);
      }
      
      showToast("Guide completed! Review it anytime from your Profile.", "success");
    } catch (error) {
      console.error("Error saving tutorial status:", error);
    }
  };
  
  // Track app state changes for background processing
  useEffect(() => {
    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);
        });
        
        // Set up a background interval to update prices periodically even when app is in background
        // This will only work on some platforms and for a limited time
        if (Platform.OS !== 'web') {
          try {
            // Try to set up a background interval that runs every 30 seconds
            // This may not work reliably on all platforms due to OS restrictions
            backgroundUpdateIntervalRef.current = setInterval(() => {
              try {
                // Update all market prices
                updateAllMarketPrices();
                
                // Save the updated data to storage
                saveChartDataToStorage().catch(err => {
                  console.error("Error saving chart data in background:", err);
                });
                
                // Check for completed trades
                const now = new Date();
                safeActiveTrades.forEach(trade => {
                  const endTime = typeof trade.endTime === 'string' 
                    ? new Date(trade.endTime) 
                    : trade.endTime;
                    
                  if (now >= endTime) {
                    completeTrade(trade.tradeId);
                  }
                });
              } catch (error) {
                console.error("Error in background update:", error);
              }
            }, 30000); // 30 seconds
          } catch (error) {
            console.error("Error setting up background interval:", error);
          }
        }
      } 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;
        }
        
        // Clear any background interval
        if (backgroundUpdateIntervalRef.current) {
          clearInterval(backgroundUpdateIntervalRef.current);
          backgroundUpdateIntervalRef.current = null;
        }
      }
      
      setAppState(nextAppState);
    });
    
    return () => {
      subscription.remove();
      
      // Clear any intervals
      if (backgroundUpdateIntervalRef.current) {
        clearInterval(backgroundUpdateIntervalRef.current);
        backgroundUpdateIntervalRef.current = null;
      }
    };
  }, [appState, saveChartDataToStorage, simulateBackgroundUpdates, updateAllMarketPrices, safeActiveTrades, completeTrade, setLastUpdateTime]);
  
  // Save chart data to storage periodically
  useEffect(() => {
    // Save chart data every 30 seconds when app is active
    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]);
  
  // Show reward modal every 5 trades
  useEffect(() => {
    if (tradeCount > 0 && tradeCount % 5 === 0) {
      setShowRewardModal(true);
    }
  }, [tradeCount]);
  
  // Check for completed trades
  useEffect(() => {
    const checkActiveTrades = () => {
      try {
        if (!Array.isArray(safeActiveTrades)) {
          console.error("activeTrades is not an array:", safeActiveTrades);
          return;
        }
        
        const now = new Date();
        safeActiveTrades.forEach(trade => {
          try {
            // Convert string dates to Date objects if needed
            const endTime = typeof trade.endTime === 'string' 
              ? new Date(trade.endTime) 
              : trade.endTime;
              
            if (now >= endTime) {
              completeTrade(trade.tradeId);
              
              // Provide haptic feedback on native platforms
              if (Platform.OS !== 'web') {
                try {
                  Vibration.vibrate(30);
                } catch (error) {
                  console.error("Vibration error:", error);
                }
              }
              
              // Show toast notification for trade result
              const market = markets[trade.market];
              if (!market) return;
              
              const currentPrice = market.currentPrice;
              const priceChange = currentPrice - trade.buyPrice;
              const isWinningTrade = (trade.tradeType === 'Buy Up' && priceChange > 0) || 
                                    (trade.tradeType === 'Buy Down' && priceChange < 0);
              
              // Use the correct currency symbol based on user location
              const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
              
              if (isWinningTrade) {
                showToast(
                  `Trade Profit: +${(trade.investmentAmount * 0.6).toFixed(2)} ${currencySymbol}`,
                  'success'
                );
              } else {
                showToast(
                  `Trade Loss: -${trade.investmentAmount.toFixed(2)} ${currencySymbol}`,
                  'error'
                );
              }
            }
          } catch (tradeError) {
            console.error("Error processing trade:", tradeError, trade);
          }
        });
      } catch (error) {
        console.error("Error checking active trades:", error);
      }
    };
    
    const tradeInterval = setInterval(checkActiveTrades, 1000);
    return () => clearInterval(tradeInterval);
  }, [safeActiveTrades, completeTrade, markets, showToast, isUserFromNigeria]);
  
  // Show location-based currency notification when country is detected
  useEffect(() => {
    if (userCountry) {
      const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
      showToast(
        `Trading with ${currencySymbol} based on your location: ${isUserFromNigeria ? 'Nigeria' : userCountry}`,
        'info'
      );
    }
  }, [userCountry, isUserFromNigeria, showToast]);
  
  // Handle scroll events
  const handleScrollBegin = useCallback(() => {
    setIsScrolling(true);
  }, []);
  
  const handleScrollEnd = useCallback(() => {
    setIsScrolling(false);
  }, []);
  
  // Handle deposit button click
  const handleDepositButtonClick = () => {
    if (isDemoAccount) {
      showToast(
        "Deposits are not available in Demo mode. Switch to Real Account to deposit funds.",
        "info"
      );
      return;
    }
    setShowDepositModal(true);
  };
  
  // Investment validation for the TradeBuyBar
  const validateInvestment = () => {
    try {
      const amount = parseFloat(investment);
      const currentBalance = isDemoAccount ? demoBalance : realBalance;
      
      if (isNaN(amount) || amount <= 0) {
        setError('Please enter a valid amount');
        return null;
      }
      
      if (amount < CONFIG.minInvestmentAmount) {
        setError(`Minimum: ${CONFIG.minInvestmentAmount} BATZ`);
        return null;
      }
      
      if (amount > currentBalance) {
        setError('Insufficient balance');
        return null;
      }
      
      return amount;
    } catch (error) {
      console.error("Error in validateInvestment:", error);
      setError('Invalid amount');
      return null;
    }
  };
  
  // Handle investment change from TradeControls
  const handleInvestmentChange = (value: string) => {
    setInvestment(value);
    setError('');
  };
  
  // Calculate responsive padding and spacing based on screen size
  const getResponsivePadding = () => {
    if (isSmallScreen) return { horizontal: 8, vertical: 6 };
    if (isMediumScreen) return { horizontal: 12, vertical: 8 };
    return { horizontal: 16, vertical: 10 }; // Large screen
  };
  
  const padding = getResponsivePadding();
  
  // Calculate bottom padding to account for the TradeBuyBar
  const bottomPadding = Platform.OS === 'ios' ? 110 : 90;
  
  // Calculate chart height based on screen size
  const getChartHeight = () => {
    if (isShortScreen) return screenHeight * 0.28;
    if (isSmallScreen) return screenHeight * 0.32;
    return screenHeight * 0.35;
  };
  
  return (
    <SafeAreaView 
      style={[styles.container, { backgroundColor: colors.background }]} 
      edges={['top']}
    >
      {theme === 'dark' && (
        <LinearGradient
          colors={['rgba(30, 39, 46, 0.8)', 'rgba(0, 0, 0, 1)']}
          style={styles.backgroundGradient}
        />
      )}
      
      <View 
        style={[
          styles.content,
          { opacity: 1 } // Force opacity to 1 to ensure visibility
        ]}
      >
        <View style={[
          styles.headerContainer,
          { paddingHorizontal: padding.horizontal, paddingVertical: padding.vertical }
        ]}>
          <View style={styles.headerRow}>
            <View style={styles.headerLeft} ref={balanceRef}>
              <AccountHeader onBalancePress={() => setShowBalanceModal(true)} />
            </View>
            <View style={styles.headerRight}>
              <View style={styles.headerRightContent}>
                <AccountTypeSwitch />
                <HeaderDepositButton 
                  onPress={handleDepositButtonClick} 
                  style={styles.headerDepositButton}
                />
              </View>
            </View>
          </View>
        </View>
        
        <View style={styles.mainContent}>
          <View ref={chartRef} style={[
            styles.chartSection,
            { height: getChartHeight() }
          ]}>
            <TradeChart marketName={currentMarketForTrade} />
          </View>
          
          {safeActiveTrades.length > 0 && (
            <View style={[
              styles.activeTradesSection,
              { 
                marginTop: 4,
                marginHorizontal: isSmallScreen ? 8 : 12
              }
            ]}>
              <ActiveTradesList trades={safeActiveTrades} />
            </View>
          )}
          
          <View style={[
            styles.refillSection,
            { 
              marginTop: 4,
              paddingHorizontal: padding.horizontal
            }
          ]}>
            <RefillButton />
          </View>
        </View>
      </View>
      
      {/* Fixed Trade Buy Bar at the bottom with investment input */}
      <TradeBuyBar 
        investment={investment}
        validateInvestment={validateInvestment}
        onInvestmentChange={handleInvestmentChange}
        error={error}
        setError={setError}
        ref={controlsRef}
      />
      
      {/* Modals */}
      <BalanceModal 
        visible={showBalanceModal} 
        onClose={() => setShowBalanceModal(false)} 
      />
      
      <DepositModal 
        visible={showDepositModal} 
        onClose={() => setShowDepositModal(false)} 
      />
      
      <RewardModal 
        visible={showRewardModal} 
        onClose={() => setShowRewardModal(false)} 
        rewardAmount={16000}
      />
      
      {/* Tutorial Overlay - Always render but control visibility with props */}
      <TutorialOverlay 
        visible={showTutorial} 
        steps={tutorialSteps} 
        onComplete={handleTutorialComplete} 
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
    zIndex: 1,
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1,
  },
  content: {
    flex: 1,
    position: 'relative',
    zIndex: 2,
  },
  headerContainer: {
    paddingVertical: 8,
    zIndex: 3,
  },
  headerRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
  },
  headerLeft: {
    flex: 1,
    marginRight: 8,
  },
  headerRight: {
    alignItems: 'flex-end',
  },
  headerRightContent: {
    alignItems: 'center',
  },
  headerDepositButton: {
    marginTop: 6,
    alignSelf: 'center',
  },
  mainContent: {
    flex: 1,
    paddingBottom: 90, // Space for the trade buy bar
  },
  chartSection: {
    zIndex: 2,
  },
  activeTradesSection: {
    zIndex: 2,
  },
  refillSection: {
    zIndex: 2,
    marginTop: 8,
  },
});