import React, { useState, useEffect, useRef, useCallback } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, ScrollView, Animated, Alert, Platform } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { LinearGradient } from 'expo-linear-gradient';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { CONFIG } from '@/constants/config';
import { useToast } from '@/context/ToastContext';
import { useTheme } from '@/context/ThemeContext';
import WithdrawModal from '@/components/WithdrawModal';
import WithdrawalHistoryItem from '@/components/WithdrawalHistoryItem';
import { ArrowRightCircle, DollarSign, Wallet, Clock, AlertCircle, ArrowRight } from 'lucide-react-native';
import { Stack } from 'expo-router';

export default function WithdrawScreen() {
  const { 
    isDemoAccount, 
    demoProfit, 
    realProfit, 
    withdrawalHistory, 
    isUserFromNigeria,
    switchAccountMode,
    activeTrades,
    userCountry
  } = useTradeStore();
  
  const { showToast } = useToast();
  const { theme, colors } = useTheme();
  
  const [showWithdrawModal, setShowWithdrawModal] = useState(false);
  const [showSwitchButton, setShowSwitchButton] = useState(false);
  const [isScrolling, setIsScrolling] = useState(false);
  
  // Animation values
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;
  const switchButtonAnim = useRef(new Animated.Value(0)).current;
  
  // Calculate available profit for withdrawal
  const currentProfit = isDemoAccount ? demoProfit : realProfit;
  const convertedProfit = isUserFromNigeria 
    ? currentProfit * CONFIG.batzToNgnRate 
    : currentProfit * CONFIG.batzToUsdRate;
  
  // Get currency symbol based on user location
  const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
  
  // Animate screen on mount
  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 800,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 800,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);
  
  // Handle withdraw button press
  const handleWithdrawPress = () => {
    if (isDemoAccount) {
      // Show toast notification that withdrawals are not available in demo mode
      showToast(
        "Withdrawals are not available in Demo mode. Switch to Real Account.",
        "error"
      );
      
      // Show the switch button with animation
      setShowSwitchButton(true);
      Animated.timing(switchButtonAnim, {
        toValue: 1,
        duration: 500,
        useNativeDriver: true,
      }).start();
      
      return;
    }
    
    // Check if user has enough profit to withdraw
    const minWithdrawalAmount = isUserFromNigeria 
      ? CONFIG.minWithdrawalAmountNG 
      : CONFIG.minWithdrawalAmountUSD;
    
    if (convertedProfit < minWithdrawalAmount) {
      showToast(
        `Minimum withdrawal amount is ${minWithdrawalAmount} ${currencySymbol}`,
        "error"
      );
      return;
    }
    
    // Open withdraw modal
    setShowWithdrawModal(true);
  };
  
  // Handle switch to real account
  const handleSwitchToReal = () => {
    if (activeTrades.length > 0) {
      Alert.alert(
        "Active Trades",
        "You cannot switch account mode while you have active trades. Please wait for your trades to complete.",
        [{ text: "OK" }]
      );
      return;
    }
    
    // Switch to real account
    switchAccountMode();
    
    // Hide the switch button
    Animated.timing(switchButtonAnim, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true,
    }).start(() => {
      setShowSwitchButton(false);
    });
    
    // Show success toast
    showToast("Switched to Real Account mode", "success");
  };
  
  // Show location-based currency notification when country is detected
  useEffect(() => {
    if (userCountry) {
      showToast(
        `Withdrawals available in ${currencySymbol} based on your location: ${isUserFromNigeria ? 'Nigeria' : userCountry}`,
        'info'
      );
    }
  }, [userCountry]);
  
  // Scroll event handlers
  const handleScrollBegin = useCallback(() => {
    setIsScrolling(true);
  }, []);
  
  const handleScrollEnd = useCallback(() => {
    setIsScrolling(false);
  }, []);
  
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={['bottom']}>
      {/* Add Stack.Screen to set the header title */}
      <Stack.Screen options={{ headerTitle: "Withdraw Funds", headerShown: true }} />
      
      {theme === 'dark' && (
        <LinearGradient
          colors={['rgba(30, 39, 46, 0.8)', 'rgba(0, 0, 0, 1)']}
          style={styles.backgroundGradient}
        />
      )}
      
      <Animated.View 
        style={[
          styles.content,
          { 
            opacity: fadeAnim,
            transform: [{ translateY: slideAnim }]
          }
        ]}
      >
        <ScrollView 
          style={styles.scrollContent}
          contentContainerStyle={styles.scrollContentContainer}
          showsVerticalScrollIndicator={false}
          scrollEventThrottle={16}
          onScrollBeginDrag={handleScrollBegin}
          onScrollEndDrag={handleScrollEnd}
          onMomentumScrollBegin={handleScrollBegin}
          onMomentumScrollEnd={handleScrollEnd}
          decelerationRate={Platform.OS === 'ios' ? 'normal' : 0.985}
          overScrollMode="never"
          bounces={false}
          bouncesZoom={false}
          alwaysBounceVertical={false}
          alwaysBounceHorizontal={false}
          removeClippedSubviews={Platform.OS !== 'web'}
          keyboardShouldPersistTaps="handled"
          keyboardDismissMode="on-drag"
        >
          <View style={[styles.balanceCard, { backgroundColor: colors.backgroundSecondary }]}>
            <LinearGradient
              colors={theme === 'dark' 
                ? ['rgba(41, 171, 226, 0.2)', 'rgba(41, 171, 226, 0.05)'] 
                : ['rgba(41, 171, 226, 0.1)', 'rgba(41, 171, 226, 0.02)']}
              style={styles.balanceCardGradient}
            />
            
            <View style={styles.balanceHeader}>
              <Wallet size={20} color={colors.primary} />
              <Text style={[styles.balanceTitle, { color: colors.text }]}>Available for Withdrawal</Text>
            </View>
            
            <Text style={[styles.balanceAmount, { color: colors.text }]}>
              {convertedProfit.toLocaleString(undefined, { maximumFractionDigits: 2})} {currencySymbol}
            </Text>
            
            <View style={[styles.balanceInfo, { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }]}>
              <Text style={[styles.balanceInfoText, { color: colors.textSecondary }]}>
                {isDemoAccount ? 'Demo mode - Withdrawals not available' : 'Real mode - Withdrawals available'}
              </Text>
            </View>
            
            <TouchableOpacity 
              style={[styles.withdrawButton, { backgroundColor: colors.primary }]}
              onPress={handleWithdrawPress}
            >
              <DollarSign size={18} color={colors.textWhite} />
              <Text style={styles.withdrawButtonText}>Withdraw Funds</Text>
            </TouchableOpacity>
          </View>
          
          {/* Switch to Real Account Button - Only shown after attempting withdrawal in demo mode */}
          {showSwitchButton && (
            <Animated.View 
              style={[
                styles.switchButtonContainer,
                {
                  opacity: switchButtonAnim,
                  transform: [
                    { 
                      translateY: switchButtonAnim.interpolate({
                        inputRange: [0, 1],
                        outputRange: [20, 0]
                      })
                    }
                  ]
                }
              ]}
            >
              <TouchableOpacity 
                style={[styles.switchButton, { backgroundColor: theme === 'dark' ? colors.bgDark : colors.backgroundSecondary }]}
                onPress={handleSwitchToReal}
                disabled={activeTrades.length > 0}
              >
                <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.switchButtonGradient}
                />
                <ArrowRightCircle size={20} color={colors.success} />
                <Text style={[styles.switchButtonText, { color: colors.success }]}>Switch to Real Account</Text>
                <ArrowRight size={16} color={colors.success} />
              </TouchableOpacity>
            </Animated.View>
          )}
          
          <View style={[styles.infoCard, { backgroundColor: colors.backgroundSecondary }]}>
            <View style={styles.infoHeader}>
              <Clock size={18} color={colors.textSecondary} />
              <Text style={[styles.infoTitle, { color: colors.text }]}>Processing Time</Text>
            </View>
            <Text style={[styles.infoText, { color: colors.textSecondary }]}>
              Withdrawals are typically processed within 24-48 hours. You will receive a notification once your withdrawal is complete.
            </Text>
          </View>
          
          <View style={[styles.infoCard, { backgroundColor: colors.backgroundSecondary }]}>
            <View style={styles.infoHeader}>
              <AlertCircle size={18} color={colors.textSecondary} />
              <Text style={[styles.infoTitle, { color: colors.text }]}>Withdrawal Requirements</Text>
            </View>
            <Text style={[styles.infoText, { color: colors.textSecondary }]}>
              Minimum withdrawal: {isUserFromNigeria ? CONFIG.minWithdrawalAmountNG + ' NGN' : CONFIG.minWithdrawalAmountUSD + ' USDT'}
            </Text>
            <Text style={[styles.infoText, { color: colors.textSecondary }]}>
              You must provide valid {isUserFromNigeria ? 'bank account details' : 'TRC-20 USDT wallet address'} and contact information.
            </Text>
          </View>
          
          <View style={styles.historySection}>
            <Text style={[styles.sectionTitle, { color: colors.text }]}>Withdrawal History</Text>
            
            {withdrawalHistory.length > 0 ? (
              withdrawalHistory.map((withdrawal, index) => (
                <WithdrawalHistoryItem 
                  key={withdrawal.id || index} 
                  withdrawal={withdrawal} 
                  index={index}
                />
              ))
            ) : (
              <View style={[styles.emptyHistoryContainer, { backgroundColor: colors.backgroundSecondary }]}>
                <Text style={[styles.emptyHistoryText, { color: colors.text }]}>No withdrawal history</Text>
                <Text style={[styles.emptyHistorySubtext, { color: colors.textSecondary }]}>
                  Your withdrawal history will appear here once you make a withdrawal
                </Text>
              </View>
            )}
          </View>
        </ScrollView>
      </Animated.View>
      
      <WithdrawModal 
        visible={showWithdrawModal}
        onClose={() => setShowWithdrawModal(false)}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  content: {
    flex: 1,
  },
  header: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  scrollContent: {
    flex: 1,
  },
  scrollContentContainer: {
    padding: 16,
    paddingBottom: 32,
  },
  balanceCard: {
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    position: 'relative',
    overflow: 'hidden',
  },
  balanceCardGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  balanceHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 12,
  },
  balanceTitle: {
    fontSize: 16,
    fontWeight: '500',
    marginLeft: 8,
  },
  balanceAmount: {
    fontSize: 28,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  balanceInfo: {
    padding: 8,
    borderRadius: 6,
    marginBottom: 16,
  },
  balanceInfoText: {
    fontSize: 12,
    textAlign: 'center',
  },
  withdrawButton: {
    borderRadius: 8,
    paddingVertical: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
  },
  withdrawButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: 'bold',
  },
  switchButtonContainer: {
    marginBottom: 16,
  },
  switchButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1.5,
    borderColor: colors.success,
    borderRadius: 8,
    paddingVertical: 14,
    paddingHorizontal: 16,
    position: 'relative',
    overflow: 'hidden',
  },
  switchButtonGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  switchButtonText: {
    fontSize: 16,
    fontWeight: 'bold',
    marginHorizontal: 8,
    flex: 1,
    textAlign: 'center',
  },
  infoCard: {
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
  },
  infoHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  infoTitle: {
    fontSize: 16,
    fontWeight: '500',
    marginLeft: 8,
  },
  infoText: {
    fontSize: 14,
    lineHeight: 20,
    marginBottom: 4,
  },
  historySection: {
    marginTop: 8,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 12,
  },
  emptyHistoryContainer: {
    borderRadius: 12,
    padding: 24,
    alignItems: 'center',
    justifyContent: 'center',
  },
  emptyHistoryText: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  emptyHistorySubtext: {
    fontSize: 14,
    textAlign: 'center',
    lineHeight: 20,
  },
});