import React, { useState, useRef, useEffect, forwardRef } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, Platform, Vibration, Dimensions, TextInput, Animated, Easing } from 'react-native';
import { ArrowUp, ArrowDown, DollarSign, Clock, Percent, AlertCircle } from 'lucide-react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { useTheme } from '@/context/ThemeContext';
import useTradeStore from '@/store/useTradeStore';
import { useToast } from '@/context/ToastContext';
import { CONFIG } from '@/constants/config';

interface TradeBuyBarProps {
  investment: string;
  validateInvestment: () => number | null;
  onInvestmentChange: (value: string) => void;
  error: string;
  setError: (error: string) => void;
}

const TradeBuyBar = forwardRef<View, TradeBuyBarProps>(({ 
  investment, 
  validateInvestment, 
  onInvestmentChange,
  error,
  setError
}, ref) => {
  const { theme, colors } = useTheme();
  const { 
    executeTrade, 
    isDemoAccount, 
    demoBalance, 
    realBalance,
    selectedTradeDuration,
    setTradeDuration,
    markets,
    currentMarketForTrade,
    isUserFromNigeria
  } = useTradeStore();
  const { showToast } = useToast();
  const [isAnimating, setIsAnimating] = useState(false);
  const [showKeyboard, setShowKeyboard] = useState(false);
  const [isInputHighlighted, setIsInputHighlighted] = useState(false);
  const [profitPercent, setProfitPercent] = useState(60);
  const [showInvestmentAlert, setShowInvestmentAlert] = useState(false);
  
  // Animation values
  const scaleAnim = useRef(new Animated.Value(1)).current;
  const inputBorderAnim = useRef(new Animated.Value(0)).current;
  const highlightAnim = useRef(new Animated.Value(0)).current;
  const alertAnim = useRef(new Animated.Value(0)).current;
  
  // Input ref for focusing
  const inputRef = useRef<TextInput>(null);
  
  // Get screen dimensions for responsive layout
  const screenWidth = Dimensions.get('window').width;
  const isSmallScreen = screenWidth < 360;
  
  const currentBalance = isDemoAccount ? demoBalance : realBalance;
  const market = markets[currentMarketForTrade];
  const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
  
  // Randomize profit percentage slightly for realism
  useEffect(() => {
    const interval = setInterval(() => {
      const newPercent = 55 + Math.floor(Math.random() * 10);
      setProfitPercent(newPercent);
    }, 60000); // Change every minute
    
    return () => {
      clearInterval(interval);
    };
  }, []);
  
  // Animate input border color when focused
  useEffect(() => {
    Animated.timing(inputBorderAnim, {
      toValue: showKeyboard ? 1 : 0,
      duration: 200,
      useNativeDriver: false,
    }).start();
  }, [showKeyboard, inputBorderAnim]);
  
  // Animate highlight effect when input needs attention
  useEffect(() => {
    if (isInputHighlighted) {
      // Create a pulsing effect
      Animated.sequence([
        Animated.timing(highlightAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: false,
        }),
        Animated.timing(highlightAnim, {
          toValue: 0.5,
          duration: 300,
          useNativeDriver: false,
        }),
        Animated.timing(highlightAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: false,
        }),
        Animated.timing(highlightAnim, {
          toValue: 0,
          duration: 500,
          useNativeDriver: false,
        }),
      ]).start(() => {
        setIsInputHighlighted(false);
      });
    }
  }, [isInputHighlighted, highlightAnim]);
  
  // Animate investment alert
  useEffect(() => {
    if (showInvestmentAlert) {
      Animated.sequence([
        Animated.timing(alertAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: true,
        }),
        Animated.delay(2000),
        Animated.timing(alertAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: true,
        }),
      ]).start(() => {
        setShowInvestmentAlert(false);
      });
    }
  }, [showInvestmentAlert, alertAnim]);
  
  const handleTrade = (type: string) => {
    try {
      // Check if investment is empty
      if (!investment || investment === '0') {
        // Highlight the input field
        setIsInputHighlighted(true);
        
        // Show investment alert
        setShowInvestmentAlert(true);
        
        // Focus the input
        handleInputFocus();
        
        // Provide haptic feedback on native platforms
        if (Platform.OS !== 'web') {
          try {
            Vibration.vibrate(20);
          } catch (error) {
            console.error("Vibration error:", error);
          }
        }
        
        return;
      }
      
      const amount = validateInvestment();
      if (amount === null) {
        // Highlight the input field
        setIsInputHighlighted(true);
        
        // Focus the input
        handleInputFocus();
        
        return;
      }
      
      setIsAnimating(true);
      
      // Provide haptic feedback on native platforms
      if (Platform.OS !== 'web') {
        try {
          Vibration.vibrate(15);
        } catch (error) {
          console.error("Vibration error:", error);
        }
      }
      
      Animated.sequence([
        Animated.timing(scaleAnim, {
          toValue: 0.95,
          duration: 100,
          useNativeDriver: true,
        }),
        Animated.timing(scaleAnim, {
          toValue: 1,
          duration: 100,
          useNativeDriver: true,
        }),
      ]).start(() => {
        setIsAnimating(false);
        const success = executeTrade(type, amount);
        
        if (success) {
          // Show toast notification for trade execution
          showToast(
            `${type} trade placed for ${amount.toLocaleString()} BATZ`,
            'info'
          );
          onInvestmentChange('');
        }
      });
    } catch (error) {
      console.error("Error in handleTrade:", error);
      setIsAnimating(false);
    }
  };
  
  const handleQuickAmount = (percentage: number) => {
    try {
      // Provide haptic feedback on native platforms
      if (Platform.OS !== 'web') {
        try {
          Vibration.vibrate(10);
        } catch (error) {
          console.error("Vibration error:", error);
        }
      }
      
      const amount = Math.floor(currentBalance * (percentage / 100));
      onInvestmentChange(amount.toString());
    } catch (error) {
      console.error("Error in handleQuickAmount:", error);
    }
  };
  
  const handleInputFocus = () => {
    if (Platform.OS === 'web') {
      // For web, focus the input directly
      if (inputRef.current) {
        inputRef.current.focus();
      }
    }
    setShowKeyboard(true);
  };
  
  // Interpolate border color for input
  const borderColor = inputBorderAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [error ? colors.error : colors.border, colors.primary]
  });
  
  // Interpolate highlight color for input
  const highlightColor = highlightAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [error ? colors.error : colors.border, colors.primary]
  });
  
  // Interpolate shadow opacity for highlight effect
  const shadowOpacity = highlightAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 0.8]
  });
  
  return (
    <View style={styles.container} ref={ref}>
      {theme === 'dark' && (
        <LinearGradient
          colors={['rgba(0, 0, 0, 0.9)', 'rgba(30, 39, 46, 0.95)']}
          style={styles.backgroundGradient}
        />
      )}
      
      {/* Investment Alert */}
      {showInvestmentAlert && (
        <Animated.View 
          style={[
            styles.investmentAlert,
            {
              opacity: alertAnim,
              transform: [
                {
                  translateY: alertAnim.interpolate({
                    inputRange: [0, 1],
                    outputRange: [20, 0],
                  }),
                },
              ],
              backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.7)',
            }
          ]}
        >
          <AlertCircle size={16} color={colors.primary} />
          <Text style={styles.investmentAlertText}>
            Please enter an investment amount first
          </Text>
        </Animated.View>
      )}
      
      <View style={styles.topSection}>
        {/* Investment Input */}
        <View style={styles.investmentContainer}>
          <View style={styles.labelContainer}>
            <DollarSign 
              size={isSmallScreen ? 12 : 14} 
              color={colors.textSecondary} 
            />
            <Text style={[
              styles.label, 
              { 
                color: colors.textSecondary,
                fontSize: isSmallScreen ? 11 : 12,
              }
            ]}>
              Investment Amount
            </Text>
          </View>
          
          <View style={styles.inputAndQuickAmountRow}>
            <Animated.View 
              style={[
                styles.inputWrapper,
                { 
                  transform: [{ scale: scaleAnim }],
                  borderColor: isInputHighlighted ? highlightColor : borderColor,
                  backgroundColor: theme === 'dark' ? 'rgba(17, 17, 17, 0.8)' : colors.backgroundSecondary,
                  borderWidth: isInputHighlighted ? 2 : 1.5,
                  shadowColor: colors.primary,
                  shadowOpacity: shadowOpacity,
                  shadowRadius: 6,
                  shadowOffset: { width: 0, height: 0 },
                  elevation: isInputHighlighted ? 4 : 1,
                }
              ]}
            >
              <TouchableOpacity 
                style={styles.input}
                onPress={handleInputFocus}
                activeOpacity={0.7}
              >
                <TextInput
                  ref={inputRef}
                  style={[
                    styles.inputText, 
                    { 
                      color: investment ? colors.text : colors.textSecondary,
                      fontSize: isSmallScreen ? 14 : 16,
                    }
                  ]}
                  value={investment}
                  onChangeText={onInvestmentChange}
                  keyboardType="numeric"
                  placeholder="0 BATZ"
                  placeholderTextColor={colors.textSecondary}
                  onFocus={() => setShowKeyboard(true)}
                  onBlur={() => setShowKeyboard(false)}
                  showSoftInputOnFocus={Platform.OS === 'web'}
                  editable={Platform.OS === 'web'}
                />
              </TouchableOpacity>
            </Animated.View>
            
            <View style={styles.quickAmountContainer}>
              <TouchableOpacity 
                style={[
                  styles.quickAmountButton, 
                  { 
                    backgroundColor: theme === 'dark' ? 'rgba(30, 39, 46, 0.9)' : 'rgba(245, 245, 245, 0.9)',
                  }
                ]}
                onPress={() => handleQuickAmount(25)}
                activeOpacity={0.7}
              >
                <Text style={[
                  styles.quickAmountText, 
                  { 
                    color: colors.text,
                    fontSize: isSmallScreen ? 9 : 10,
                  }
                ]}>25%</Text>
              </TouchableOpacity>
              <TouchableOpacity 
                style={[
                  styles.quickAmountButton, 
                  { 
                    backgroundColor: theme === 'dark' ? 'rgba(30, 39, 46, 0.9)' : 'rgba(245, 245, 245, 0.9)',
                  }
                ]}
                onPress={() => handleQuickAmount(50)}
                activeOpacity={0.7}
              >
                <Text style={[
                  styles.quickAmountText, 
                  { 
                    color: colors.text,
                    fontSize: isSmallScreen ? 9 : 10,
                  }
                ]}>50%</Text>
              </TouchableOpacity>
              <TouchableOpacity 
                style={[
                  styles.quickAmountButton, 
                  { 
                    backgroundColor: theme === 'dark' ? 'rgba(30, 39, 46, 0.9)' : 'rgba(245, 245, 245, 0.9)',
                  }
                ]}
                onPress={() => handleQuickAmount(100)}
                activeOpacity={0.7}
              >
                <Text style={[
                  styles.quickAmountText, 
                  { 
                    color: colors.text,
                    fontSize: isSmallScreen ? 9 : 10,
                  }
                ]}>MAX</Text>
              </TouchableOpacity>
            </View>
          </View>
          
          {error ? (
            <Animated.Text 
              style={[
                styles.errorText,
                { 
                  transform: [{ scale: scaleAnim }],
                  fontSize: isSmallScreen ? 10 : 11,
                }
              ]}
            >
              {error}
            </Animated.Text>
          ) : null}
        </View>
        
        {/* Duration Selection */}
        <View style={styles.durationContainer}>
          <View style={styles.labelContainer}>
            <Clock 
              size={isSmallScreen ? 12 : 14} 
              color={colors.textSecondary} 
            />
            <Text style={[
              styles.label, 
              { 
                color: colors.textSecondary,
                fontSize: isSmallScreen ? 11 : 12,
              }
            ]}>
              Duration
            </Text>
          </View>
          
          <View style={styles.durationButtons}>
            {CONFIG.tradeDurations.map((duration) => (
              <TouchableOpacity
                key={duration.value}
                style={[
                  styles.durationButton,
                  selectedTradeDuration === duration.value && styles.activeDurationButton,
                  { 
                    backgroundColor: theme === 'dark' 
                      ? 'rgba(30, 39, 46, 0.9)' 
                      : 'rgba(245, 245, 245, 0.9)',
                    borderColor: selectedTradeDuration === duration.value ? colors.primary : 'transparent',
                  }
                ]}
                onPress={() => {
                  // Provide haptic feedback on native platforms
                  if (Platform.OS !== 'web') {
                    try {
                      Vibration.vibrate(10);
                    } catch (error) {
                      console.error("Vibration error:", error);
                    }
                  }
                  setTradeDuration(duration.value);
                }}
                activeOpacity={0.7}
              >
                {theme === 'dark' && selectedTradeDuration === duration.value && (
                  <LinearGradient
                    colors={['rgba(41, 171, 226, 0.1)', 'rgba(41, 171, 226, 0.02)']}
                    style={styles.durationGradient}
                  />
                )}
                <Text style={[
                  styles.durationButtonText,
                  { 
                    color: selectedTradeDuration === duration.value ? colors.primary : colors.text,
                    fontSize: isSmallScreen ? 10 : 11,
                  }
                ]}>
                  {duration.label}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </View>
      
      {/* Profit Info */}
      <View style={styles.profitInfoContainer}>
        <Percent 
          size={isSmallScreen ? 12 : 14} 
          color={colors.textSecondary} 
        />
        <Text style={[
          styles.profitInfoText, 
          { 
            color: colors.textSecondary,
            fontSize: isSmallScreen ? 10 : 11,
          }
        ]}>
          Profit: <Text style={[
            styles.profitPercent, 
            { color: colors.success }
          ]}>{profitPercent}%</Text> • Price: {market?.currentPrice.toFixed(2)} {currencySymbol}
        </Text>
      </View>
      
      <View style={styles.tradeButtons}>
        <TouchableOpacity 
          style={[
            styles.tradeButton, 
            styles.buyUpButton,
            { 
              backgroundColor: theme === 'dark' ? 'rgba(17, 17, 17, 0.8)' : colors.backgroundSecondary,
              borderColor: colors.success,
            }
          ]}
          onPress={() => handleTrade('Buy Up')}
          disabled={isAnimating}
          activeOpacity={0.7}
        >
          <LinearGradient
            colors={theme === 'dark' 
              ? ['rgba(46, 204, 113, 0.2)', 'rgba(46, 204, 113, 0.05)'] 
              : ['rgba(46, 204, 113, 0.1)', 'rgba(46, 204, 113, 0.02)']}
            style={styles.buttonGradient}
          />
          <ArrowUp 
            size={isSmallScreen ? 18 : 20} 
            color={colors.success} 
          />
          <View style={styles.buttonTextContainer}>
            <Text style={[
              styles.tradeButtonText, 
              { 
                color: colors.success,
                fontSize: isSmallScreen ? 13 : 15,
              }
            ]}>
              Buy Up
            </Text>
            <Text style={[
              styles.tradeButtonSubtext, 
              { 
                color: colors.textSecondary,
                fontSize: isSmallScreen ? 10 : 11,
              }
            ]}>
              ({profitPercent}% Profit)
            </Text>
          </View>
        </TouchableOpacity>
        
        <TouchableOpacity 
          style={[
            styles.tradeButton, 
            styles.buyDownButton,
            { 
              backgroundColor: theme === 'dark' ? 'rgba(17, 17, 17, 0.8)' : colors.backgroundSecondary,
              borderColor: colors.error,
            }
          ]}
          onPress={() => handleTrade('Buy Down')}
          disabled={isAnimating}
          activeOpacity={0.7}
        >
          <LinearGradient
            colors={theme === 'dark' 
              ? ['rgba(231, 76, 60, 0.2)', 'rgba(231, 76, 60, 0.05)'] 
              : ['rgba(231, 76, 60, 0.1)', 'rgba(231, 76, 60, 0.02)']}
            style={styles.buttonGradient}
          />
          <ArrowDown 
            size={isSmallScreen ? 18 : 20} 
            color={colors.error} 
          />
          <View style={styles.buttonTextContainer}>
            <Text style={[
              styles.tradeButtonText, 
              { 
                color: colors.error,
                fontSize: isSmallScreen ? 13 : 15,
              }
            ]}>
              Buy Down
            </Text>
            <Text style={[
              styles.tradeButtonSubtext, 
              { 
                color: colors.textSecondary,
                fontSize: isSmallScreen ? 10 : 11,
              }
            ]}>
              ({profitPercent}% Profit)
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    </View>
  );
});

export default TradeBuyBar;

const styles = StyleSheet.create({
  container: {
    width: '100%',
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    paddingHorizontal: 12,
    paddingTop: 8,
    paddingBottom: 10,
    borderTopWidth: 1,
    borderTopColor: 'rgba(0, 0, 0, 0.1)',
    zIndex: 100,
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: -1,
  },
  topSection: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 6,
  },
  investmentContainer: {
    flex: 1,
    marginRight: 8,
  },
  durationContainer: {
    width: '40%',
  },
  labelContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 4,
  },
  label: {
    fontWeight: '500',
    marginLeft: 4,
  },
  inputAndQuickAmountRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    width: '100%',
  },
  inputWrapper: {
    borderRadius: 10,
    overflow: 'hidden',
    flex: 1,
    marginRight: 4,
  },
  input: {
    justifyContent: 'center',
    alignItems: 'flex-end',
    width: '100%',
    paddingVertical: 8,
    paddingHorizontal: 10,
  },
  inputText: {
    textAlign: 'right',
    width: '100%',
    height: '100%',
    padding: 0,
    fontWeight: '600',
  },
  quickAmountContainer: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    gap: 4,
  },
  quickAmountButton: {
    paddingHorizontal: 6,
    paddingVertical: 4,
    borderRadius: 6,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
    alignItems: 'center',
  },
  quickAmountText: {
    fontWeight: '600',
  },
  errorText: {
    color: '#e74c3c',
    marginTop: 2,
    fontWeight: '500',
    width: '100%',
    textAlign: 'center',
  },
  durationButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    gap: 4,
  },
  durationButton: {
    flex: 1,
    paddingVertical: 6,
    borderRadius: 6,
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1.5,
    position: 'relative',
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 1,
  },
  durationGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  activeDurationButton: {
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
  },
  durationButtonText: {
    fontWeight: '600',
  },
  profitInfoContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 6,
    width: '100%',
  },
  profitInfoText: {
    marginLeft: 4,
  },
  profitPercent: {
    fontWeight: 'bold',
  },
  tradeButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    gap: 10,
  },
  tradeButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 12,
    gap: 8,
    position: 'relative',
    overflow: 'hidden',
    borderWidth: 1.5,
  },
  buttonGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  buyUpButton: {
    borderWidth: 1.5,
  },
  buyDownButton: {
    borderWidth: 1.5,
  },
  buttonTextContainer: {
    flexDirection: 'column',
    alignItems: 'center',
  },
  tradeButtonText: {
    fontWeight: 'bold',
  },
  tradeButtonSubtext: {
    fontSize: 11,
  },
  investmentAlert: {
    position: 'absolute',
    top: -40,
    left: '10%',
    right: '10%',
    padding: 8,
    borderRadius: 8,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 101,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 5,
  },
  investmentAlertText: {
    color: '#FFFFFF',
    marginLeft: 8,
    fontWeight: '500',
    fontSize: 12,
  },
});