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

interface AccountHeaderProps {
  onBalancePress: () => void;
}

export default function AccountHeader({ onBalancePress }: AccountHeaderProps) {
  const { 
    isDemoAccount, 
    demoBalance, 
    realBalance, 
    demoProfit, 
    realProfit,
    isUserFromNigeria,
    userCurrency
  } = useTradeStore();
  
  const { theme, colors } = useTheme();
  
  const [showProfit, setShowProfit] = useState(false);
  
  // Animation values
  const rotateAnim = useRef(new Animated.Value(0)).current;
  const balanceAnim = useRef(new Animated.Value(1)).current;
  const profitAnim = useRef(new Animated.Value(0)).current;
  
  // Get current balance and profit based on account mode
  const currentBalance = isDemoAccount ? demoBalance : realBalance;
  const currentProfit = isDemoAccount ? demoProfit : realProfit;
  
  // Currency symbol based on user location
  const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
  
  // Toggle between balance and profit display
  const toggleDisplay = () => {
    // Start rotation animation
    Animated.timing(rotateAnim, {
      toValue: showProfit ? 0 : 1,
      duration: 300,
      useNativeDriver: true,
      easing: Easing.bezier(0.25, 0.1, 0.25, 1),
    }).start();
    
    // Fade out current display
    Animated.parallel([
      Animated.timing(balanceAnim, {
        toValue: showProfit ? 1 : 0,
        duration: 200,
        useNativeDriver: true,
      }),
      Animated.timing(profitAnim, {
        toValue: showProfit ? 0 : 1,
        duration: 200,
        useNativeDriver: true,
      }),
    ]).start();
    
    // Toggle state
    setShowProfit(!showProfit);
  };
  
  // Interpolate rotation for the toggle icon
  const rotate = rotateAnim.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '180deg'],
  });
  
  // Get screen dimensions for responsive layout
  const screenWidth = Dimensions.get('window').width;
  const isSmallScreen = screenWidth < 360;
  
  return (
    <TouchableOpacity 
      style={[
        styles.container, 
        { 
          backgroundColor: theme === 'dark' ? 'rgba(30, 39, 46, 0.5)' : colors.backgroundSecondary,
          zIndex: 3,
          padding: isSmallScreen ? 8 : 10,
        }
      ]}
      onPress={onBalancePress}
      activeOpacity={0.7}
    >
      {theme === 'dark' && (
        <LinearGradient
          colors={['rgba(41, 171, 226, 0.1)', 'rgba(41, 171, 226, 0.02)']}
          style={styles.gradient}
        />
      )}
      
      <View style={styles.iconContainer}>
        <Wallet size={isSmallScreen ? 16 : 18} color={colors.primary} />
      </View>
      
      <View style={styles.balanceContainer}>
        <Text style={[
          styles.label, 
          { 
            color: colors.textSecondary,
            fontSize: isSmallScreen ? 10 : 11
          }
        ]}>
          {showProfit ? 'Total Profit' : 'Balance'}
        </Text>
        
        <View style={styles.amountRow}>
          <Animated.View 
            style={[
              styles.amountContainer,
              { 
                opacity: balanceAnim,
                position: 'absolute',
                transform: [
                  { 
                    translateY: balanceAnim.interpolate({
                      inputRange: [0, 1],
                      outputRange: [-20, 0],
                    })
                  }
                ]
              }
            ]}
          >
            <Text style={[
              styles.amount, 
              { 
                color: colors.text,
                fontSize: isSmallScreen ? 14 : 16
              }
            ]}>
              {currentBalance.toLocaleString()} BATZ
            </Text>
          </Animated.View>
          
          <Animated.View 
            style={[
              styles.amountContainer,
              { 
                opacity: profitAnim,
                position: 'absolute',
                transform: [
                  { 
                    translateY: profitAnim.interpolate({
                      inputRange: [0, 1],
                      outputRange: [20, 0],
                    })
                  }
                ]
              }
            ]}
          >
            <View style={styles.profitRow}>
              {currentProfit > 0 ? (
                <TrendingUp size={isSmallScreen ? 12 : 14} color={colors.success} style={styles.profitIcon} />
              ) : (
                <TrendingDown size={isSmallScreen ? 12 : 14} color={colors.error} style={styles.profitIcon} />
              )}
              <Text 
                style={[
                  styles.amount, 
                  { 
                    color: currentProfit >= 0 ? colors.success : colors.error,
                    fontSize: isSmallScreen ? 14 : 16
                  }
                ]}
              >
                {currentProfit.toLocaleString()} {currencySymbol}
              </Text>
            </View>
          </Animated.View>
        </View>
      </View>
      
      <TouchableOpacity 
        style={styles.toggleButton}
        onPress={toggleDisplay}
      >
        <Animated.View style={{ transform: [{ rotate }] }}>
          <ChevronRight size={isSmallScreen ? 14 : 16} color={colors.textSecondary} />
        </Animated.View>
      </TouchableOpacity>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 12,
    position: 'relative',
    overflow: 'hidden',
  },
  gradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  iconContainer: {
    marginRight: 8,
  },
  balanceContainer: {
    flex: 1,
  },
  label: {
    marginBottom: 1,
  },
  amountRow: {
    height: 20,
    position: 'relative',
  },
  amountContainer: {
    left: 0,
    right: 0,
  },
  amount: {
    fontWeight: 'bold',
  },
  profitRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  profitIcon: {
    marginRight: 4,
  },
  toggleButton: {
    padding: 4,
  },
});

// Add missing import
import { Dimensions } from 'react-native';