import React, { useEffect, useRef, useState } from 'react';
import { StyleSheet, View, Text, Modal, TouchableOpacity, FlatList, Animated, Image, Platform } from 'react-native';
import { X, Check, ChevronUp, ChevronDown } from 'lucide-react-native';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { LinearGradient } from 'expo-linear-gradient';

interface MarketSelectionModalProps {
  visible: boolean;
  onClose: () => void;
}

export default function MarketSelectionModal({ visible, onClose }: MarketSelectionModalProps) {
  // Get store values at the top level
  const { markets, currentMarketForTrade, setCurrentMarketForTrade } = useTradeStore();
  
  // Animation values
  const slideAnim = useRef(new Animated.Value(Platform.OS === 'web' ? 0 : 100)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  
  // State declarations at the top level
  const [selectedMarket, setSelectedMarket] = useState(currentMarketForTrade);
  const [error, setError] = useState<string | null>(null);
  
  // Create refs for each market item animation
  // IMPORTANT: We need to create these at the top level, not inside renderItem
  const marketItemAnimations = useRef<{[key: string]: Animated.Value}>({});
  
  // Initialize animation values for all markets
  useEffect(() => {
    const marketKeys = Object.keys(markets);
    marketKeys.forEach(key => {
      if (!marketItemAnimations.current[key]) {
        marketItemAnimations.current[key] = new Animated.Value(1);
      }
    });
  }, [markets]);
  
  useEffect(() => {
    if (visible) {
      setSelectedMarket(currentMarketForTrade);
      
      // Slide up animation when modal becomes visible
      Animated.parallel([
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        })
      ]).start();
    } else {
      // Reset animation value when modal is hidden
      if (Platform.OS === 'web') {
        slideAnim.setValue(0);
      } else {
        slideAnim.setValue(100);
      }
      opacityAnim.setValue(0);
      setError(null);
    }
  }, [visible, currentMarketForTrade]);
  
  // Animate selected market item
  useEffect(() => {
    if (marketItemAnimations.current[selectedMarket]) {
      Animated.sequence([
        Animated.timing(marketItemAnimations.current[selectedMarket], {
          toValue: 1.05,
          duration: 150,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(marketItemAnimations.current[selectedMarket], {
          toValue: 1,
          duration: 150,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();
    }
  }, [selectedMarket]);
  
  const handleMarketSelect = (marketKey: string) => {
    try {
      setSelectedMarket(marketKey);
    } catch (error) {
      console.error("Error selecting market:", error);
      setError("Failed to select market. Please try again.");
    }
  };
  
  const handleConfirm = () => {
    try {
      setCurrentMarketForTrade(selectedMarket);
      
      // Animate out before closing
      Animated.parallel([
        Animated.timing(slideAnim, {
          toValue: Platform.OS === 'web' ? 0 : 100,
          duration: 250,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(opacityAnim, {
          toValue: 0,
          duration: 250,
          useNativeDriver: Platform.OS !== 'web',
        })
      ]).start(() => {
        onClose();
      });
    } catch (error) {
      console.error("Error confirming market selection:", error);
      setError("Failed to change market. Please try again.");
    }
  };
  
  const handleClose = () => {
    // Animate out before closing
    Animated.parallel([
      Animated.timing(slideAnim, {
        toValue: Platform.OS === 'web' ? 0 : 100,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(opacityAnim, {
        toValue: 0,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      })
    ]).start(() => {
      onClose();
    });
  };
  
  const renderMarketItem = ({ item }: { item: [string, any] }) => {
    const [marketKey, marketData] = item;
    const isSelected = selectedMarket === marketKey;
    
    // Calculate price change percentage
    const lastPrice = marketData.chartDataPoints[marketData.chartDataPoints.length - 1];
    const prevPrice = marketData.chartDataPoints[marketData.chartDataPoints.length - 2] || lastPrice;
    const priceChange = lastPrice - prevPrice;
    const priceChangePercent = (priceChange / prevPrice) * 100;
    const isPriceUp = priceChange >= 0;
    
    // Get the animation value for this market
    const scaleAnim = marketItemAnimations.current[marketKey] || new Animated.Value(1);
    
    return (
      <Animated.View
        style={[
          styles.marketItem,
          isSelected && styles.selectedMarketItem,
          Platform.OS !== 'web' ? { transform: [{ scale: scaleAnim }] } : {}
        ]}
      >
        <TouchableOpacity
          style={styles.marketItemContent}
          onPress={() => handleMarketSelect(marketKey)}
          activeOpacity={0.7}
        >
          <LinearGradient
            colors={isSelected ? 
              ['rgba(41, 171, 226, 0.2)', 'rgba(41, 171, 226, 0.05)'] : 
              ['rgba(30, 39, 46, 0.5)', 'rgba(30, 39, 46, 0.2)']}
            style={styles.marketItemGradient}
          />
          
          <View style={styles.marketItemLeft}>
            <Image 
              source={{ uri: marketData.iconUrl }}
              style={styles.marketIcon}
              resizeMode="contain"
            />
            <View>
              <Text style={styles.marketName}>{marketData.displayName}</Text>
              <Text style={styles.marketPrice}>{marketData.currentPrice.toFixed(2)}</Text>
            </View>
          </View>
          
          <View style={styles.marketItemRight}>
            <View style={[
              styles.priceChangeContainer,
              isPriceUp ? styles.priceUp : styles.priceDown
            ]}>
              {isPriceUp ? 
                <ChevronUp size={14} color={colors.success} /> : 
                <ChevronDown size={14} color={colors.error} />
              }
              <Text style={[
                styles.priceChangeText,
                isPriceUp ? styles.priceUpText : styles.priceDownText
              ]}>
                {Math.abs(priceChangePercent).toFixed(2)}%
              </Text>
            </View>
            
            {isSelected && (
              <View style={styles.checkContainer}>
                <Check size={18} color={colors.primary} />
              </View>
            )}
          </View>
        </TouchableOpacity>
      </Animated.View>
    );
  };
  
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
      onRequestClose={handleClose}
    >
      <View style={styles.modalContainer}>
        <Animated.View 
          style={[
            styles.modalContent,
            Platform.OS === 'web' 
              ? { 
                  opacity: opacityAnim,
                  bottom: 0,
                } 
              : { 
                  transform: [{ translateY: slideAnim }],
                  opacity: opacityAnim
                }
          ]}
        >
          <View style={styles.header}>
            <Text style={styles.headerTitle}>Select Market</Text>
            <TouchableOpacity style={styles.closeButton} onPress={handleClose}>
              <X size={20} color={colors.textWhite} />
            </TouchableOpacity>
          </View>
          
          {error ? (
            <View style={styles.errorContainer}>
              <Text style={styles.errorText}>{error}</Text>
              <TouchableOpacity 
                style={styles.retryButton}
                onPress={() => {
                  setError(null);
                  setSelectedMarket(currentMarketForTrade);
                }}
              >
                <Text style={styles.retryButtonText}>Retry</Text>
              </TouchableOpacity>
            </View>
          ) : (
            <FlatList
              data={Object.entries(markets)}
              renderItem={renderMarketItem}
              keyExtractor={([key]) => key}
              contentContainerStyle={styles.marketsList}
              showsVerticalScrollIndicator={false}
            />
          )}
          
          <View style={styles.footer}>
            <TouchableOpacity 
              style={styles.confirmButton}
              onPress={handleConfirm}
            >
              <Text style={styles.confirmButtonText}>Confirm Selection</Text>
            </TouchableOpacity>
          </View>
        </Animated.View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modalContainer: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: colors.bgBlack,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    maxHeight: '80%',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: -5 },
    shadowOpacity: 0.3,
    shadowRadius: 10,
    elevation: 10,
    position: 'relative',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(74, 101, 114, 0.2)',
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: colors.textWhite,
  },
  closeButton: {
    padding: 8,
    borderRadius: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
  },
  marketsList: {
    padding: 16,
  },
  marketItem: {
    marginBottom: 12,
    borderRadius: 12,
    overflow: 'hidden',
    borderWidth: 1,
    borderColor: 'rgba(74, 101, 114, 0.2)',
  },
  selectedMarketItem: {
    borderColor: colors.primary,
    borderWidth: 1.5,
  },
  marketItemContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    position: 'relative',
  },
  marketItemGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  marketItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  marketIcon: {
    width: 32,
    height: 32,
    marginRight: 12,
  },
  marketName: {
    fontSize: 16,
    fontWeight: 'bold',
    color: colors.textWhite,
  },
  marketPrice: {
    fontSize: 14,
    color: colors.textLightGray,
  },
  marketItemRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  priceChangeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
    marginRight: 8,
  },
  priceUp: {
    backgroundColor: 'rgba(46, 204, 113, 0.1)',
  },
  priceDown: {
    backgroundColor: 'rgba(231, 76, 60, 0.1)',
  },
  priceChangeText: {
    fontSize: 12,
    fontWeight: '500',
  },
  priceUpText: {
    color: colors.success,
  },
  priceDownText: {
    color: colors.error,
  },
  checkContainer: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  footer: {
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: 'rgba(74, 101, 114, 0.2)',
  },
  confirmButton: {
    backgroundColor: colors.primary,
    paddingVertical: 14,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
    shadowColor: colors.primary,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 3,
  },
  confirmButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: 'bold',
  },
  errorContainer: {
    padding: 20,
    alignItems: 'center',
  },
  errorText: {
    color: colors.error,
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: colors.primary,
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderRadius: 8,
  },
  retryButtonText: {
    color: colors.textWhite,
    fontWeight: 'bold',
  },
});