import React, { useState, useRef, useEffect } from 'react';
import { StyleSheet, View, Text, Modal, TouchableOpacity, FlatList, Alert, SafeAreaView, StatusBar, ActivityIndicator, Platform, Animated, Easing } from 'react-native';
import { X, AlertTriangle, ArrowLeft, CheckCircle, AlertCircle } from 'lucide-react-native';
import { colors } from '@/constants/colors';
import useTradeStore from '@/store/useTradeStore';
import { CONFIG } from '@/constants/config';
import { useToast } from '@/context/ToastContext';
import { WebView } from 'react-native-webview';

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

export default function DepositModal({ visible, onClose }: DepositModalProps) {
  const { 
    isDemoAccount, 
    isUserFromNigeria, 
    selectedDepositMethod, 
    setSelectedDepositMethod,
    userCountry,
    switchAccountMode
  } = useTradeStore();
  
  const { showToast } = useToast();
  const webViewRef = useRef<WebView>(null);
  
  // Animation values
  const slideAnim = useRef(new Animated.Value(Platform.OS === 'web' ? 0 : 500)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  
  // State for multi-step process
  const [step, setStep] = useState<'select' | 'warning' | 'payment' | 'processing' | 'success' | 'demo-warning'>('select');
  const [selectedAmount, setSelectedAmount] = useState<number | null>(null);
  const [isWebViewLoading, setIsWebViewLoading] = useState(true);
  
  // Get deposit amounts based on user location
  const depositAmounts = isUserFromNigeria 
    ? CONFIG.depositAmountsNGN 
    : CONFIG.depositAmountsUSD;
  
  // Get currency symbol based on user location
  const currencySymbol = isUserFromNigeria ? 'NGN' : 'USD';
  const conversionRate = isUserFromNigeria 
    ? CONFIG.depositBatzToNgnRate 
    : CONFIG.depositBatzToUsdRate;
  
  // Check if in demo mode when modal opens
  useEffect(() => {
    if (visible) {
      // Animate in from right side
      Animated.parallel([
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 400,
          useNativeDriver: Platform.OS !== 'web',
          easing: Easing.out(Easing.cubic),
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();
      
      // If in demo mode, show demo warning
      if (isDemoAccount) {
        setStep('demo-warning');
        return;
      }
      
      // If we have a selected deposit method from another screen, skip to warning step
      if (selectedDepositMethod && selectedAmount === null) {
        // Auto-select the middle amount option
        const middleIndex = Math.floor(depositAmounts.length / 2);
        setSelectedAmount(depositAmounts[middleIndex]);
        setStep('warning');
        
        // Show toast notification about the selected method
        showToast(`${selectedDepositMethod} selected for deposit`, 'info');
      } else {
        // Otherwise start at the select step
        setStep('select');
      }
    } else {
      // Reset animation values
      slideAnim.setValue(Platform.OS === 'web' ? 0 : 500);
      opacityAnim.setValue(0);
    }
  }, [visible, selectedDepositMethod, isDemoAccount]);
  
  // Clear selected deposit method when modal is closed
  useEffect(() => {
    if (!visible) {
      // Only clear if we're not in the middle of a deposit process
      if (step === 'select' || step === 'success' || step === 'demo-warning') {
        setSelectedDepositMethod(null);
      }
    }
  }, [visible, step]);
  
  const handleClose = () => {
    // Animate out before closing
    Animated.parallel([
      Animated.timing(slideAnim, {
        toValue: Platform.OS === 'web' ? 0 : 500,
        duration: 300,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(opacityAnim, {
        toValue: 0,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
    ]).start(() => {
      setStep('select');
      setSelectedAmount(null);
      setSelectedDepositMethod(null);
      onClose();
    });
  };
  
  const handleSelectAmount = (amount: number) => {
    if (isDemoAccount) {
      setStep('demo-warning');
      return;
    }
    
    setSelectedAmount(amount);
    setStep('warning');
  };
  
  const handleConfirmDeposit = () => {
    if (!selectedAmount) return;
    setStep('payment');
  };
  
  const handlePaymentComplete = () => {
    setStep('processing');
    
    // Simulate processing time
    setTimeout(() => {
      setStep('success');
    }, 3000);
  };
  
  const handleSwitchToRealAccount = () => {
    switchAccountMode();
    showToast('Switched to Real Account', 'success');
    handleClose();
  };
  
  const renderDepositOption = ({ item }: { item: number }) => (
    <TouchableOpacity 
      style={[
        styles.depositButton,
        selectedAmount === item && styles.depositButtonSelected
      ]}
      onPress={() => handleSelectAmount(item)}
    >
      <Text style={[
        styles.depositButtonText,
        selectedAmount === item && styles.depositButtonTextSelected
      ]}>
        {item.toLocaleString()} BATZ Coins - {(item * conversionRate).toLocaleString()} {currencySymbol}
      </Text>
    </TouchableOpacity>
  );
  
  const renderStepContent = () => {
    switch (step) {
      case 'demo-warning':
        return (
          <View style={styles.demoWarningContainer}>
            <AlertCircle size={60} color={colors.accent} />
            <Text style={styles.demoWarningTitle}>Demo Account</Text>
            <Text style={styles.demoWarningText}>
              Deposits are not available in Demo Account mode. Switch to Real Account to deposit funds.
            </Text>
            
            <View style={styles.demoWarningInfo}>
              <Text style={styles.demoWarningInfoText}>
                • Demo accounts use virtual funds for practice
              </Text>
              <Text style={styles.demoWarningInfoText}>
                • Switch to Real Account to deposit actual money
              </Text>
              <Text style={styles.demoWarningInfoText}>
                • Real Account trades can result in actual profits
              </Text>
            </View>
            
            <TouchableOpacity 
              style={styles.switchAccountButton}
              onPress={handleSwitchToRealAccount}
            >
              <Text style={styles.switchAccountButtonText}>Switch to Real Account</Text>
            </TouchableOpacity>
            
            <TouchableOpacity 
              style={styles.cancelButton}
              onPress={handleClose}
            >
              <Text style={styles.cancelButtonText}>Cancel</Text>
            </TouchableOpacity>
          </View>
        );
        
      case 'select':
        return (
          <>
            <Text style={styles.modalTitle}>Add Funds</Text>
            <Text style={styles.modalSubtitle}>Select an amount to deposit</Text>
            
            <FlatList
              data={depositAmounts}
              renderItem={renderDepositOption}
              keyExtractor={(item) => item.toString()}
              contentContainerStyle={styles.depositOptions}
            />
          </>
        );
        
      case 'warning':
        return (
          <>
            <View style={styles.warningHeader}>
              <AlertTriangle size={28} color={colors.accent} />
              <Text style={styles.warningTitle}>IMPORTANT NOTICE</Text>
            </View>
            
            <View style={styles.warningContent}>
              <Text style={styles.warningText}>
                Do not close this page. Wait for payment verification, then click "Claim Deposit." 
              </Text>
              
              <Text style={[styles.warningText, styles.warningHighlight]}>
                Ignoring these steps may result in lost of funds. No refunds.
              </Text>
              
              <View style={styles.amountContainer}>
                <Text style={styles.amountLabel}>Amount to deposit:</Text>
                <Text style={styles.amountValue}>
                  {selectedAmount?.toLocaleString()} BATZ Coins
                </Text>
                <Text style={styles.amountConversion}>
                  ({(selectedAmount! * conversionRate).toLocaleString()} {currencySymbol})
                </Text>
              </View>
              
              {selectedDepositMethod && (
                <View style={styles.methodContainer}>
                  <Text style={styles.methodLabel}>Payment method:</Text>
                  <Text style={styles.methodValue}>{selectedDepositMethod}</Text>
                </View>
              )}
            </View>
            
            <View style={styles.warningActions}>
              <TouchableOpacity 
                style={styles.backButton} 
                onPress={() => setStep('select')}
              >
                <ArrowLeft size={20} color={colors.textWhite} />
                <Text style={styles.backButtonText}>Back</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.proceedButton}
                onPress={handleConfirmDeposit}
              >
                <Text style={styles.proceedButtonText}>I Understand, Proceed</Text>
              </TouchableOpacity>
            </View>
          </>
        );
        
      case 'payment':
        return (
          <View style={styles.webViewContainer}>
            {isWebViewLoading && (
              <View style={styles.webViewLoading}>
                <ActivityIndicator size="large" color={colors.primary} />
                <Text style={styles.webViewLoadingText}>Loading payment gateway...</Text>
              </View>
            )}
            
            {Platform.OS === 'web' ? (
              <iframe
                src="https://batsapp.emakemrnd.com.ng/Tradepro/testtrade.html"
                style={{
                  width: '100%',
                  height: '100%',
                  border: 'none',
                }}
                onLoad={() => setIsWebViewLoading(false)}
              />
            ) : (
              <WebView
                ref={webViewRef}
                source={{ uri: "https://batsapp.emakemrnd.com.ng/Tradepro/testtrade.html" }}
                style={styles.webView}
                onLoad={() => setIsWebViewLoading(false)}
                onError={(syntheticEvent) => {
                  const { nativeEvent } = syntheticEvent;
                  console.error('WebView error: ', nativeEvent);
                  Alert.alert(
                    "Connection Error",
                    "Failed to connect to payment gateway. Please try again later.",
                    [
                      { text: "Go Back", onPress: () => setStep('warning') }
                    ]
                  );
                }}
              />
            )}
            
            <View style={styles.webViewFooter}>
              <TouchableOpacity 
                style={styles.webViewBackButton}
                onPress={() => setStep('warning')}
              >
                <ArrowLeft size={20} color={colors.textWhite} />
                <Text style={styles.webViewBackButtonText}>Cancel Payment</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.webViewCompleteButton}
                onPress={handlePaymentComplete}
              >
                <Text style={styles.webViewCompleteButtonText}>Payment Complete</Text>
              </TouchableOpacity>
            </View>
          </View>
        );
        
      case 'processing':
        return (
          <View style={styles.processingContainer}>
            <ActivityIndicator size="large" color={colors.primary} />
            <Text style={styles.processingTitle}>Processing Payment</Text>
            <Text style={styles.processingText}>
              Please wait while we process your payment. Do not close this window.
            </Text>
            
            <View style={styles.processingSteps}>
              <View style={styles.processingStep}>
                <View style={[styles.stepIndicator, styles.stepActive]}>
                  <Text style={styles.stepNumber}>1</Text>
                </View>
                <Text style={styles.stepText}>Initiating payment</Text>
              </View>
              
              <View style={styles.processingStep}>
                <View style={[styles.stepIndicator, styles.stepActive]}>
                  <Text style={styles.stepNumber}>2</Text>
                </View>
                <Text style={styles.stepText}>Verifying transaction</Text>
              </View>
              
              <View style={styles.processingStep}>
                <View style={styles.stepIndicator}>
                  <Text style={styles.stepNumber}>3</Text>
                </View>
                <Text style={styles.stepText}>Crediting account</Text>
              </View>
            </View>
          </View>
        );
        
      case 'success':
        return (
          <View style={styles.successContainer}>
            <CheckCircle size={60} color={colors.success} />
            <Text style={styles.successTitle}>Deposit Successful!</Text>
            <Text style={styles.successText}>
              Your deposit of {selectedAmount?.toLocaleString()} BATZ Coins has been credited to your account.
            </Text>
            
            <TouchableOpacity 
              style={styles.doneButton}
              onPress={handleClose}
            >
              <Text style={styles.doneButtonText}>Done</Text>
            </TouchableOpacity>
          </View>
        );
    }
  };
  
  return (
    <Modal
      visible={visible}
      animationType="none"
      transparent={true}
      onRequestClose={() => {
        if (step === 'payment' || step === 'processing') {
          Alert.alert(
            'Warning',
            'Closing now may result in lost funds. Are you sure?',
            [
              { text: 'Stay', style: 'cancel' },
              { text: 'Close Anyway', style: 'destructive', onPress: handleClose }
            ]
          );
        } else {
          handleClose();
        }
      }}
    >
      <StatusBar barStyle="light-content" backgroundColor={colors.bgDark} />
      <SafeAreaView style={styles.container}>
        <Animated.View 
          style={[
            styles.animatedContainer,
            {
              opacity: opacityAnim,
              transform: Platform.OS === 'web' 
                ? [] 
                : [{ translateX: slideAnim }]
            }
          ]}
        >
          {step !== 'payment' && step !== 'processing' && step !== 'success' && (
            <TouchableOpacity 
              style={styles.closeButton} 
              onPress={() => {
                if (step === 'warning') {
                  setStep('select');
                } else {
                  handleClose();
                }
              }}
            >
              <X size={24} color={colors.textLightGray} />
            </TouchableOpacity>
          )}
          
          <View style={styles.content}>
            {renderStepContent()}
          </View>
          
          {step === 'select' && (
            <TouchableOpacity style={styles.cancelButton} onPress={handleClose}>
              <Text style={styles.cancelButtonText}>Cancel</Text>
            </TouchableOpacity>
          )}
        </Animated.View>
      </SafeAreaView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.bgDark,
  },
  animatedContainer: {
    flex: 1,
  },
  closeButton: {
    position: 'absolute',
    top: 16,
    right: 16,
    zIndex: 10,
    padding: 8,
  },
  content: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
  },
  modalTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: colors.textWhite,
    marginBottom: 8,
    textAlign: 'center',
  },
  modalSubtitle: {
    fontSize: 16,
    color: colors.textLightGray,
    marginBottom: 24,
    textAlign: 'center',
  },
  depositOptions: {
    gap: 12,
    paddingBottom: 20,
  },
  depositButton: {
    backgroundColor: colors.bgBlack,
    borderWidth: 1,
    borderColor: colors.borderGray,
    borderRadius: 12,
    padding: 16,
    marginBottom: 4,
    alignItems: 'center',
  },
  depositButtonSelected: {
    borderColor: colors.primary,
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
  },
  depositButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: '500',
  },
  depositButtonTextSelected: {
    color: colors.primary,
    fontWeight: 'bold',
  },
  cancelButton: {
    backgroundColor: '#191919',
    borderRadius: 12,
    padding: 16,
    margin: 20,
    alignItems: 'center',
  },
  cancelButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: 'bold',
  },
  
  // Demo warning styles
  demoWarningContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    padding: 20,
  },
  demoWarningTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: colors.textWhite,
    marginTop: 24,
    marginBottom: 12,
  },
  demoWarningText: {
    fontSize: 16,
    color: colors.textLightGray,
    textAlign: 'center',
    marginBottom: 24,
    lineHeight: 24,
  },
  demoWarningInfo: {
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    borderRadius: 12,
    padding: 16,
    width: '100%',
    marginBottom: 24,
  },
  demoWarningInfoText: {
    fontSize: 14,
    color: colors.textWhite,
    marginBottom: 10,
    lineHeight: 20,
  },
  switchAccountButton: {
    backgroundColor: colors.primary,
    borderRadius: 12,
    paddingVertical: 16,
    paddingHorizontal: 24,
    width: '100%',
    alignItems: 'center',
    marginBottom: 12,
  },
  switchAccountButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: 'bold',
  },
  
  // Warning step styles
  warningHeader: {
    alignItems: 'center',
    marginBottom: 24,
    flexDirection: 'row',
    justifyContent: 'center',
    gap: 12,
  },
  warningTitle: {
    fontSize: 22,
    fontWeight: 'bold',
    color: colors.accent,
  },
  warningContent: {
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    borderRadius: 12,
    padding: 20,
    marginBottom: 24,
  },
  warningText: {
    fontSize: 16,
    color: colors.textWhite,
    marginBottom: 16,
    lineHeight: 24,
  },
  warningHighlight: {
    color: colors.accent,
    fontWeight: 'bold',
  },
  amountContainer: {
    marginTop: 20,
    padding: 16,
    backgroundColor: 'rgba(255, 255, 255, 0.05)',
    borderRadius: 8,
    alignItems: 'center',
  },
  amountLabel: {
    fontSize: 14,
    color: colors.textLightGray,
    marginBottom: 8,
  },
  amountValue: {
    fontSize: 24,
    fontWeight: 'bold',
    color: colors.textWhite,
  },
  amountConversion: {
    fontSize: 16,
    color: colors.primary,
    marginTop: 4,
  },
  methodContainer: {
    marginTop: 16,
    padding: 16,
    backgroundColor: 'rgba(41, 171, 226, 0.1)',
    borderRadius: 8,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: colors.primary,
  },
  methodLabel: {
    fontSize: 14,
    color: colors.textLightGray,
    marginBottom: 8,
  },
  methodValue: {
    fontSize: 18,
    fontWeight: 'bold',
    color: colors.primary,
  },
  warningActions: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: 12,
  },
  backButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 12,
    padding: 16,
    flex: 1,
    justifyContent: 'center',
    gap: 8,
  },
  backButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: '500',
  },
  proceedButton: {
    backgroundColor: colors.primary,
    borderRadius: 12,
    padding: 16,
    flex: 2,
    alignItems: 'center',
  },
  proceedButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: 'bold',
  },
  
  // WebView styles
  webViewContainer: {
    flex: 1,
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: colors.bgDark,
  },
  webView: {
    flex: 1,
    backgroundColor: colors.bgDark,
  },
  webViewLoading: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: colors.bgDark,
    zIndex: 10,
  },
  webViewLoadingText: {
    color: colors.textWhite,
    marginTop: 16,
    fontSize: 16,
  },
  webViewFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 16,
    backgroundColor: colors.bgBlack,
    borderTopWidth: 1,
    borderTopColor: 'rgba(255, 255, 255, 0.1)',
  },
  webViewBackButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 12,
    padding: 12,
    flex: 1,
    justifyContent: 'center',
    gap: 8,
    marginRight: 8,
  },
  webViewBackButtonText: {
    color: colors.textWhite,
    fontSize: 14,
    fontWeight: '500',
  },
  webViewCompleteButton: {
    backgroundColor: colors.success,
    borderRadius: 12,
    padding: 12,
    flex: 1.5,
    alignItems: 'center',
  },
  webViewCompleteButtonText: {
    color: colors.textWhite,
    fontSize: 14,
    fontWeight: 'bold',
  },
  
  // Processing step styles
  processingContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  processingTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: colors.textWhite,
    marginTop: 24,
    marginBottom: 12,
  },
  processingText: {
    fontSize: 16,
    color: colors.textLightGray,
    textAlign: 'center',
    marginBottom: 40,
    maxWidth: '80%',
  },
  processingSteps: {
    width: '100%',
    marginTop: 20,
  },
  processingStep: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 24,
  },
  stepIndicator: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 16,
  },
  stepActive: {
    backgroundColor: colors.primary,
  },
  stepNumber: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: 'bold',
  },
  stepText: {
    color: colors.textWhite,
    fontSize: 16,
  },
  
  // Success step styles
  successContainer: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  successTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: colors.textWhite,
    marginTop: 24,
    marginBottom: 12,
  },
  successText: {
    fontSize: 16,
    color: colors.textLightGray,
    textAlign: 'center',
    marginBottom: 40,
    maxWidth: '80%',
  },
  doneButton: {
    backgroundColor: colors.primary,
    borderRadius: 12,
    paddingVertical: 16,
    paddingHorizontal: 40,
    alignItems: 'center',
    marginTop: 20,
  },
  doneButtonText: {
    color: colors.textWhite,
    fontSize: 16,
    fontWeight: 'bold',
  },
});