import React, { useRef, useEffect, useState } from 'react';
import { StyleSheet, View, Text, Modal, TouchableOpacity, Animated, Platform, Dimensions } from 'react-native';
import { X, TrendingUp, TrendingDown, Wallet } from 'lucide-react-native';
import useTradeStore from '@/store/useTradeStore';
import { CONFIG } from '@/constants/config';
import { LinearGradient } from 'expo-linear-gradient';
import { useTheme } from '@/context/ThemeContext';

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

export default function BalanceModal({ visible, onClose }: BalanceModalProps) {
  const { 
    isDemoAccount, 
    demoBalance, 
    demoProfit, 
    realBalance, 
    realProfit,
    userCurrency,
    isUserFromNigeria
  } = useTradeStore();
  
  const { colors, theme } = useTheme();
  
  // Get screen dimensions for responsive layout
  const screenWidth = Dimensions.get('window').width;
  const screenHeight = Dimensions.get('window').height;
  const isSmallScreen = screenWidth < 360;
  const isShortScreen = screenHeight < 700;
  
  // State for expanded sections
  const [expandedSection, setExpandedSection] = useState<string | null>(null);
  
  // Animation values
  const scaleAnim = useRef(new Animated.Value(0.9)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(Platform.OS === 'web' ? 0 : 50)).current;
  
  // Animation for expanded sections
  const expandAnim = useRef(new Animated.Value(0)).current;
  
  useEffect(() => {
    if (visible) {
      // Animate modal when it becomes visible
      Animated.parallel([
        Animated.timing(scaleAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();
    } else {
      // Reset animation values when modal is hidden
      scaleAnim.setValue(0.9);
      opacityAnim.setValue(0);
      slideAnim.setValue(Platform.OS === 'web' ? 0 : 50);
      setExpandedSection(null);
    }
  }, [visible]);
  
  // Animate expanded section
  useEffect(() => {
    Animated.timing(expandAnim, {
      toValue: expandedSection ? 1 : 0,
      duration: 300,
      useNativeDriver: false,
    }).start();
  }, [expandedSection]);
  
  const handleClose = () => {
    // Animate out before closing
    Animated.parallel([
      Animated.timing(scaleAnim, {
        toValue: 0.9,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(opacityAnim, {
        toValue: 0,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(slideAnim, {
        toValue: Platform.OS === 'web' ? 0 : 50,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
    ]).start(() => {
      onClose();
    });
  };
  
  const toggleSection = (section: string) => {
    setExpandedSection(expandedSection === section ? null : section);
  };
  
  const currentBalance = isDemoAccount ? demoBalance : realBalance;
  const currentProfit = isDemoAccount ? demoProfit : realProfit;
  
  const formatBalance = (balance: number) => {
    return balance.toLocaleString();
  };
  
  const convertProfit = (profit: number) => {
    return isUserFromNigeria 
      ? profit * CONFIG.batzToNgnRate 
      : profit * CONFIG.batzToUsdRate;
  };
  
  // Determine if profit is positive, negative, or zero
  const isProfitPositive = currentProfit > 0;
  const isProfitNegative = currentProfit < 0;
  
  // Calculate expanded section height
  const expandedHeight = expandAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 120]
  });
  
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
      onRequestClose={handleClose}
    >
      <View style={styles.modalOverlay}>
        <Animated.View 
          style={[
            styles.modalContent,
            {
              backgroundColor: colors.backgroundSecondary,
              opacity: opacityAnim,
              transform: Platform.OS === 'web' 
                ? [{ scale: scaleAnim }] 
                : [{ scale: scaleAnim }, { translateY: slideAnim }],
              width: isSmallScreen ? '95%' : '90%',
              maxWidth: 340,
              padding: isSmallScreen ? 16 : 20,
            }
          ]}
        >
          {theme === 'dark' && (
            <LinearGradient
              colors={['rgba(52, 73, 94, 0.4)', 'rgba(30, 39, 46, 0.8)']}
              style={styles.modalGradient}
            />
          )}
          
          <TouchableOpacity style={styles.closeButton} onPress={handleClose}>
            <X size={isSmallScreen ? 18 : 20} color={colors.textSecondary} />
          </TouchableOpacity>
          
          <Text style={[
            styles.modalTitle, 
            { 
              color: colors.text,
              fontSize: isSmallScreen ? 18 : 20,
              marginBottom: isShortScreen ? 16 : 20,
            }
          ]}>
            Account Balance
          </Text>
          
          <View style={styles.accountTypeIndicator}>
            <View style={[
              styles.statusDot,
              isDemoAccount ? styles.demoDot : styles.realDot
            ]} />
            <Text style={[
              styles.accountTypeText,
              isDemoAccount ? styles.demoText : styles.realText,
              { fontSize: isSmallScreen ? 14 : 16 }
            ]}>
              {isDemoAccount ? 'Demo Account' : 'Real Account'}
            </Text>
          </View>
          
          <TouchableOpacity 
            style={[
              styles.balanceContainer,
              { marginBottom: isShortScreen ? 12 : 16 }
            ]}
            onPress={() => toggleSection('balance')}
            activeOpacity={0.7}
          >
            <View style={styles.balanceHeader}>
              <View style={styles.balanceIconContainer}>
                <Wallet size={isSmallScreen ? 18 : 20} color={colors.primary} />
              </View>
              <View style={styles.balanceTextContainer}>
                <Text style={[
                  styles.balanceLabel, 
                  { 
                    color: colors.textSecondary,
                    fontSize: isSmallScreen ? 12 : 14
                  }
                ]}>
                  Current Balance
                </Text>
                <Text style={[
                  styles.balanceValue, 
                  { 
                    color: colors.text,
                    fontSize: isSmallScreen ? 28 : 32
                  }
                ]}>
                  {formatBalance(Math.floor(currentBalance))}
                  <Text style={[
                    styles.balanceUnit, 
                    { 
                      color: colors.textSecondary,
                      fontSize: isSmallScreen ? 16 : 18
                    }
                  ]}> BATZ</Text>
                </Text>
              </View>
            </View>
            
            {/* Expanded Balance Section */}
            <Animated.View 
              style={[
                styles.expandedSection,
                { 
                  height: expandedSection === 'balance' ? expandedHeight : 0,
                  overflow: 'hidden'
                }
              ]}
            >
              <View style={[
                styles.expandedContent,
                { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.05)' }
              ]}>
                <Text style={[styles.expandedText, { color: colors.textSecondary }]}>
                  Your BATZ coins are used to place trades. Each BATZ coin has a fixed value that can be converted to {isUserFromNigeria ? 'NGN' : 'USDT'} when withdrawing.
                </Text>
                <View style={styles.conversionRow}>
                  <Text style={[styles.conversionText, { color: colors.textSecondary }]}>
                    1 BATZ = {isUserFromNigeria ? CONFIG.batzToNgnRate.toFixed(2) + ' NGN' : CONFIG.batzToUsdRate.toFixed(2) + ' USDT'}
                  </Text>
                </View>
              </View>
            </Animated.View>
          </TouchableOpacity>
          
          <TouchableOpacity 
            style={[
              styles.profitContainer, 
              { 
                backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.05)',
                marginBottom: isShortScreen ? 12 : 16
              }
            ]}
            onPress={() => toggleSection('profit')}
            activeOpacity={0.7}
          >
            <View style={styles.profitHeader}>
              <View style={styles.profitIconContainer}>
                {isProfitPositive ? (
                  <TrendingUp size={isSmallScreen ? 18 : 20} color={colors.success} />
                ) : (
                  <TrendingDown size={isSmallScreen ? 18 : 20} color={colors.error} />
                )}
              </View>
              <View style={styles.profitTextContainer}>
                <Text style={[
                  styles.profitLabel, 
                  { 
                    color: colors.textSecondary,
                    fontSize: isSmallScreen ? 12 : 14
                  }
                ]}>
                  Total Profit
                </Text>
                <Text style={[
                  styles.profitValue,
                  isProfitPositive ? styles.profitPositive : 
                  isProfitNegative ? styles.profitNegative : 
                  { color: colors.text },
                  { fontSize: isSmallScreen ? 22 : 24 }
                ]}>
                  {convertProfit(currentProfit).toFixed(2)} 
                  <Text style={[
                    styles.currencyUnit, 
                    { 
                      color: colors.textSecondary,
                      fontSize: isSmallScreen ? 14 : 16
                    }
                  ]}> {isUserFromNigeria ? 'NGN' : 'USDT'}</Text>
                </Text>
              </View>
            </View>
            
            {/* Expanded Profit Section */}
            <Animated.View 
              style={[
                styles.expandedSection,
                { 
                  height: expandedSection === 'profit' ? expandedHeight : 0,
                  overflow: 'hidden'
                }
              ]}
            >
              <View style={styles.expandedContent}>
                <Text style={[styles.expandedText, { color: colors.textSecondary }]}>
                  Your profit is calculated from successful trades. Winning trades earn 60% profit on your investment amount.
                </Text>
                <View style={styles.profitBreakdown}>
                  <View style={styles.profitBreakdownItem}>
                    <Text style={[styles.profitBreakdownLabel, { color: colors.textSecondary }]}>
                      Win Rate:
                    </Text>
                    <Text style={[styles.profitBreakdownValue, { color: colors.text }]}>
                      {Math.floor(Math.random() * 20) + 50}%
                    </Text>
                  </View>
                  <View style={styles.profitBreakdownItem}>
                    <Text style={[styles.profitBreakdownLabel, { color: colors.textSecondary }]}>
                      Best Trade:
                    </Text>
                    <Text style={[styles.profitBreakdownValue, { color: colors.success }]}>
                      +{(Math.random() * 1000).toFixed(2)} {isUserFromNigeria ? 'NGN' : 'USDT'}
                    </Text>
                  </View>
                </View>
              </View>
            </Animated.View>
          </TouchableOpacity>
          
          <View style={styles.infoContainer}>
            <Text style={[
              styles.infoText, 
              { 
                color: colors.textSecondary,
                fontSize: isSmallScreen ? 12 : 13,
                lineHeight: isSmallScreen ? 16 : 18
              }
            ]}>
              {isDemoAccount 
                ? "Demo mode lets you practice trading without real money. Switch to Real Account when you're ready to trade with actual funds."
                : "You're trading with real funds. All profits can be withdrawn to your bank account or crypto wallet."}
            </Text>
          </View>
        </Animated.View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  modalContent: {
    borderRadius: 16,
    position: 'relative',
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 10 },
    shadowOpacity: 0.3,
    shadowRadius: 20,
    elevation: 10,
  },
  modalGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  closeButton: {
    position: 'absolute',
    top: 12,
    right: 12,
    padding: 8,
    zIndex: 10,
  },
  modalTitle: {
    fontWeight: 'bold',
    textAlign: 'center',
  },
  accountTypeIndicator: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 20,
  },
  statusDot: {
    width: 10,
    height: 10,
    borderRadius: 5,
    marginRight: 8,
  },
  demoDot: {
    backgroundColor: '#E74C3C',
  },
  realDot: {
    backgroundColor: '#2ECC71',
  },
  accountTypeText: {
    fontWeight: '600',
  },
  demoText: {
    color: '#E74C3C',
  },
  realText: {
    color: '#2ECC71',
  },
  balanceContainer: {
    borderRadius: 12,
    overflow: 'hidden',
  },
  balanceHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  balanceIconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  balanceTextContainer: {
    flex: 1,
  },
  balanceLabel: {
    marginBottom: 4,
  },
  balanceValue: {
    fontWeight: '700',
  },
  balanceUnit: {
    fontWeight: '500',
  },
  profitContainer: {
    borderRadius: 12,
    padding: 16,
    overflow: 'hidden',
  },
  profitHeader: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  profitIconContainer: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  profitTextContainer: {
    flex: 1,
  },
  profitLabel: {
    marginBottom: 4,
  },
  profitValue: {
    fontWeight: '600',
  },
  currencyUnit: {
    fontWeight: '500',
  },
  profitPositive: {
    color: '#2ECC71',
  },
  profitNegative: {
    color: '#E74C3C',
  },
  infoContainer: {
    paddingTop: 8,
  },
  infoText: {
    textAlign: 'center',
  },
  expandedSection: {
    marginTop: 12,
  },
  expandedContent: {
    padding: 12,
    borderRadius: 8,
  },
  expandedText: {
    fontSize: 12,
    lineHeight: 18,
  },
  conversionRow: {
    marginTop: 8,
    alignItems: 'center',
  },
  conversionText: {
    fontSize: 14,
    fontWeight: '600',
  },
  profitBreakdown: {
    marginTop: 8,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  profitBreakdownItem: {
    flex: 1,
  },
  profitBreakdownLabel: {
    fontSize: 12,
  },
  profitBreakdownValue: {
    fontSize: 14,
    fontWeight: '600',
  },
});