import React, { useState, useEffect, useRef } from 'react';
import { StyleSheet, View, Text, Modal, TouchableOpacity, TextInput, ScrollView, Alert, ActivityIndicator, Animated, Platform } from 'react-native';
import { X, Check, ArrowRightCircle } 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 { LinearGradient } from 'expo-linear-gradient';
import { useTheme } from '@/context/ThemeContext';

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

export default function WithdrawModal({ visible, onClose }: WithdrawModalProps) {
  const { 
    isDemoAccount, 
    isUserFromNigeria, 
    demoProfit, 
    realProfit,
    recordWithdrawal,
    switchAccountMode,
    activeTrades,
    userCurrency,
    userCountry
  } = useTradeStore();
  
  const { theme, colors } = useTheme();
  const { showToast } = useToast();
  
  // Animation values
  const slideAnim = useRef(new Animated.Value(Platform.OS === 'web' ? 0 : -300)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  
  const [accountName, setAccountName] = useState('');
  const [accountNumber, setAccountNumber] = useState('');
  const [bankName, setBankName] = useState('');
  const [usdtAddress, setUsdtAddress] = useState('');
  const [telegramUsername, setTelegramUsername] = useState('');
  const [contactNumber, setContactNumber] = useState('');
  const [withdrawAmount, setWithdrawAmount] = useState('');
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isProcessing, setIsProcessing] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [showSwitchButton, setShowSwitchButton] = useState(false);
  
  const currentProfit = isDemoAccount ? demoProfit : realProfit;
  const minWithdrawalAmount = isUserFromNigeria 
    ? CONFIG.minWithdrawalAmountNG 
    : CONFIG.minWithdrawalAmountUSD;
  
  const convertProfit = (profit: number) => {
    return isUserFromNigeria 
      ? profit * CONFIG.batzToNgnRate 
      : profit * CONFIG.batzToUsdRate;
  };
  
  // Reset form when modal is opened
  useEffect(() => {
    if (visible) {
      resetForm();
      // Show switch button if in demo mode
      setShowSwitchButton(isDemoAccount);
      
      // Animate in from left side
      Animated.parallel([
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();
    } else {
      // Reset animation values
      slideAnim.setValue(Platform.OS === 'web' ? 0 : -300);
      opacityAnim.setValue(0);
    }
  }, [visible, isDemoAccount]);
  
  const resetForm = () => {
    setAccountName('');
    setAccountNumber('');
    setBankName('');
    setUsdtAddress('');
    setTelegramUsername('');
    setContactNumber('');
    setWithdrawAmount('');
    setErrors({});
    setIsProcessing(false);
    setIsSuccess(false);
  };
  
  const handleClose = () => {
    // Animate out before closing
    Animated.parallel([
      Animated.timing(slideAnim, {
        toValue: Platform.OS === 'web' ? 0 : -300,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
      Animated.timing(opacityAnim, {
        toValue: 0,
        duration: 250,
        useNativeDriver: Platform.OS !== 'web',
      }),
    ]).start(() => {
      onClose();
    });
  };
  
  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    
    // Check if in demo mode
    if (isDemoAccount) {
      Alert.alert(
        'Demo Account',
        'Withdrawals are not available in Demo Account. Switch to Real Account.',
        [
          { 
            text: 'Switch to Real', 
            onPress: handleSwitchToReal,
            style: 'default'
          },
          { 
            text: 'Cancel', 
            style: 'cancel' 
          }
        ]
      );
      return false;
    }
    
    // Validate amount
    const amount = parseFloat(withdrawAmount);
    if (isNaN(amount) || amount <= 0) {
      newErrors.withdrawAmount = 'Enter a valid amount';
    } else if (amount < minWithdrawalAmount) {
      newErrors.withdrawAmount = `Minimum withdrawal: ${minWithdrawalAmount} ${isUserFromNigeria ? 'NGN' : 'USDT'}`;
    } else if (amount > convertProfit(currentProfit)) {
      newErrors.withdrawAmount = 'Insufficient funds';
    }
    
    // Validate other fields based on country
    if (isUserFromNigeria) {
      if (!accountName.trim()) newErrors.accountName = 'Account name is required';
      if (!accountNumber.trim()) newErrors.accountNumber = 'Account number is required';
      if (accountNumber.trim() && !/^\d{10}$/.test(accountNumber.trim())) {
        newErrors.accountNumber = 'Account number must be 10 digits';
      }
      if (!bankName.trim()) newErrors.bankName = 'Bank name is required';
    } else {
      if (!/^T[a-zA-Z0-9]{33}$/.test(usdtAddress)) {
        newErrors.usdtAddress = 'Invalid TRC-20 USDT Address';
      }
    }
    
    // Common validations
    if (!telegramUsername.trim() || !/^@[a-zA-Z0-9_]{5,32}$/.test(telegramUsername)) {
      newErrors.telegramUsername = 'Invalid Telegram username (e.g. @username)';
    }
    
    if (!contactNumber.trim()) {
      newErrors.contactNumber = 'Contact number is required';
    } else if (!/^\+?[0-9]{10,15}$/.test(contactNumber.trim())) {
      newErrors.contactNumber = 'Invalid contact number format';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  const handleSwitchToReal = () => {
    if (activeTrades.length > 0) {
      showToast(
        "Cannot switch account mode while you have active trades.",
        "error"
      );
      return;
    }
    
    // Switch to real account
    switchAccountMode();
    
    // Show success toast
    showToast("Switched to Real Account mode", "success");
    
    // Close modal and reset
    setTimeout(() => {
      handleClose();
    }, 500);
  };
  
  const handleWithdraw = () => {
    if (!validateForm()) return;
    
    const amount = parseFloat(withdrawAmount);
    setIsProcessing(true);
    
    // Simulate processing delay
    setTimeout(() => {
      // Record the withdrawal
      recordWithdrawal({
        id: Date.now().toString(),
        amount,
        method: isUserFromNigeria ? 'Bank Transfer' : 'USDT',
        status: 'pending',
        timestamp: new Date().toISOString(),
        accountDetails: isUserFromNigeria 
          ? `${accountName} - ${bankName} - ${accountNumber}`
          : usdtAddress
      });
      
      setIsProcessing(false);
      setIsSuccess(true);
      
      // Show toast notification for withdrawal
      showToast(
        `Withdrawal of ${amount.toFixed(2)} ${isUserFromNigeria ? 'NGN' : 'USDT'} initiated`,
        'success'
      );
      
      // Close modal after showing success for a moment
      setTimeout(() => {
        handleClose();
      }, 2000);
    }, 2000);
  };
  
  // Display the correct currency symbol based on user's location
  const currencySymbol = isUserFromNigeria ? 'NGN' : 'USDT';
  
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
      onRequestClose={handleClose}
    >
      <View style={styles.modalOverlay}>
        <Animated.View 
          style={[
            styles.modalContent, 
            { 
              backgroundColor: theme === 'dark' ? colors.bgDark : colors.backgroundSecondary,
              opacity: opacityAnim,
              transform: Platform.OS === 'web' 
                ? [] 
                : [{ translateX: slideAnim }]
            }
          ]}
        >
          <TouchableOpacity 
            style={styles.closeButton} 
            onPress={handleClose}
            disabled={isProcessing}
          >
            <X size={20} color={colors.textSecondary} />
          </TouchableOpacity>
          
          <Text style={[styles.modalTitle, { color: colors.text }]}>
            {isSuccess ? 'Withdrawal Successful' : 'Initiate Withdrawal'}
          </Text>
          
          {isSuccess ? (
            <View style={styles.successContainer}>
              <View style={styles.successIconContainer}>
                <Check size={40} color={colors.success} />
              </View>
              <Text style={[styles.successText, { color: colors.text }]}>
                Your withdrawal of {parseFloat(withdrawAmount).toLocaleString()} {currencySymbol} has been initiated successfully.
              </Text>
              <Text style={[styles.successSubtext, { color: colors.textSecondary }]}>
                You will receive a confirmation message once processed.
              </Text>
            </View>
          ) : isProcessing ? (
            <View style={styles.processingContainer}>
              <ActivityIndicator size="large" color={colors.primary} />
              <Text style={[styles.processingText, { color: colors.text }]}>Processing your withdrawal...</Text>
              <Text style={[styles.processingSubtext, { color: colors.textSecondary }]}>Please do not close this screen.</Text>
            </View>
          ) : (
            <ScrollView style={styles.formContainer}>
              {showSwitchButton && (
                <TouchableOpacity 
                  style={[
                    styles.switchAccountButton,
                    { backgroundColor: theme === 'dark' ? colors.bgBlack : 'rgba(46, 204, 113, 0.05)' }
                  ]}
                  onPress={handleSwitchToReal}
                  disabled={activeTrades.length > 0}
                >
                  <LinearGradient
                    colors={['rgba(46, 204, 113, 0.2)', 'rgba(46, 204, 113, 0.05)']}
                    style={styles.switchButtonGradient}
                  />
                  <ArrowRightCircle size={18} color={colors.success} />
                  <Text style={[styles.switchButtonText, { color: colors.success }]}>
                    Switch to Real Account
                  </Text>
                </TouchableOpacity>
              )}
              
              <View style={[
                styles.availableContainer, 
                { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }
              ]}>
                <Text style={[styles.availableLabel, { color: colors.textSecondary }]}>Available for withdrawal:</Text>
                <Text style={[styles.availableAmount, { color: colors.primary }]}>
                  {convertProfit(currentProfit).toFixed(2)} {currencySymbol}
                </Text>
              </View>
              
              {isUserFromNigeria ? (
                <>
                  <View style={styles.inputGroup}>
                    <TextInput
                      style={[
                        styles.input, 
                        { 
                          backgroundColor: theme === 'dark' ? '#111' : '#F5F5F5',
                          borderColor: colors.border,
                          color: colors.text
                        }
                      ]}
                      placeholder="Account Name"
                      placeholderTextColor={colors.textSecondary}
                      value={accountName}
                      onChangeText={setAccountName}
                    />
                    {errors.accountName && <Text style={styles.errorText}>{errors.accountName}</Text>}
                  </View>
                  
                  <View style={styles.inputGroup}>
                    <TextInput
                      style={[
                        styles.input, 
                        { 
                          backgroundColor: theme === 'dark' ? '#111' : '#F5F5F5',
                          borderColor: colors.border,
                          color: colors.text
                        }
                      ]}
                      placeholder="Account Number"
                      placeholderTextColor={colors.textSecondary}
                      value={accountNumber}
                      onChangeText={setAccountNumber}
                      keyboardType="numeric"
                      maxLength={10}
                    />
                    {errors.accountNumber && <Text style={styles.errorText}>{errors.accountNumber}</Text>}
                  </View>
                  
                  <View style={styles.inputGroup}>
                    <TextInput
                      style={[
                        styles.input, 
                        { 
                          backgroundColor: theme === 'dark' ? '#111' : '#F5F5F5',
                          borderColor: colors.border,
                          color: colors.text
                        }
                      ]}
                      placeholder="Bank Name"
                      placeholderTextColor={colors.textSecondary}
                      value={bankName}
                      onChangeText={setBankName}
                    />
                    {errors.bankName && <Text style={styles.errorText}>{errors.bankName}</Text>}
                  </View>
                </>
              ) : (
                <View style={styles.inputGroup}>
                  <TextInput
                    style={[
                      styles.input, 
                      { 
                        backgroundColor: theme === 'dark' ? '#111' : '#F5F5F5',
                        borderColor: colors.border,
                        color: colors.text
                      }
                    ]}
                    placeholder="TRC-20 USDT Tether wallet"
                    placeholderTextColor={colors.textSecondary}
                    value={usdtAddress}
                    onChangeText={setUsdtAddress}
                  />
                  {errors.usdtAddress && <Text style={styles.errorText}>{errors.usdtAddress}</Text>}
                </View>
              )}
              
              <View style={styles.inputGroup}>
                <TextInput
                  style={[
                    styles.input, 
                    { 
                      backgroundColor: theme === 'dark' ? '#111' : '#F5F5F5',
                      borderColor: colors.border,
                      color: colors.text
                    }
                  ]}
                  placeholder="Telegram Username (@username)"
                  placeholderTextColor={colors.textSecondary}
                  value={telegramUsername}
                  onChangeText={setTelegramUsername}
                />
                {errors.telegramUsername && <Text style={styles.errorText}>{errors.telegramUsername}</Text>}
              </View>
              
              <View style={styles.inputGroup}>
                <TextInput
                  style={[
                    styles.input, 
                    { 
                      backgroundColor: theme === 'dark' ? '#111' : '#F5F5F5',
                      borderColor: colors.border,
                      color: colors.text
                    }
                  ]}
                  placeholder="Contact Number"
                  placeholderTextColor={colors.textSecondary}
                  value={contactNumber}
                  onChangeText={setContactNumber}
                  keyboardType="phone-pad"
                />
                {errors.contactNumber && <Text style={styles.errorText}>{errors.contactNumber}</Text>}
              </View>
              
              <View style={styles.inputGroup}>
                <TextInput
                  style={[
                    styles.input, 
                    { 
                      backgroundColor: theme === 'dark' ? '#111' : '#F5F5F5',
                      borderColor: colors.border,
                      color: colors.text
                    }
                  ]}
                  placeholder={`Amount to Withdraw (Min: ${minWithdrawalAmount} ${currencySymbol})`}
                  placeholderTextColor={colors.textSecondary}
                  value={withdrawAmount}
                  onChangeText={setWithdrawAmount}
                  keyboardType="numeric"
                />
                {errors.withdrawAmount && <Text style={styles.errorText}>{errors.withdrawAmount}</Text>}
              </View>
              
              <View style={[
                styles.disclaimerContainer, 
                { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.05)' }
              ]}>
                <Text style={[styles.disclaimerText, { color: colors.textSecondary }]}>
                  By proceeding, you confirm that the provided information is correct. Withdrawals typically process within 24-48 hours.
                </Text>
              </View>
            </ScrollView>
          )}
          
          {!isProcessing && !isSuccess && !showSwitchButton && (
            <View style={styles.buttonContainer}>
              <TouchableOpacity 
                style={[
                  styles.withdrawButton, 
                  { 
                    backgroundColor: theme === 'dark' ? colors.bgBlack : colors.backgroundSecondary,
                    borderColor: colors.primary
                  }
                ]} 
                onPress={handleWithdraw}
              >
                <Text style={[styles.withdrawButtonText, { color: colors.primary }]}>Withdraw</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={[
                  styles.cancelButton, 
                  { backgroundColor: theme === 'dark' ? '#191919' : '#E5E5E5' }
                ]} 
                onPress={handleClose}
              >
                <Text style={[styles.cancelButtonText, { color: colors.text }]}>Cancel</Text>
              </TouchableOpacity>
            </View>
          )}
          
          {!isProcessing && !isSuccess && showSwitchButton && (
            <TouchableOpacity 
              style={[
                styles.cancelButton, 
                { backgroundColor: theme === 'dark' ? '#191919' : '#E5E5E5' }
              ]} 
              onPress={handleClose}
            >
              <Text style={[styles.cancelButtonText, { color: colors.text }]}>Close</Text>
            </TouchableOpacity>
          )}
        </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: 10,
    padding: 20,
    width: '90%',
    maxWidth: 400,
    maxHeight: '80%',
    position: 'relative',
  },
  closeButton: {
    position: 'absolute',
    top: 10,
    right: 10,
    padding: 5,
    zIndex: 10,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 15,
    textAlign: 'center',
  },
  formContainer: {
    marginBottom: 15,
  },
  switchAccountButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1.5,
    borderColor: colors.success,
    borderRadius: 8,
    paddingVertical: 12,
    paddingHorizontal: 16,
    marginBottom: 16,
    gap: 10,
    position: 'relative',
    overflow: 'hidden',
  },
  switchButtonGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  switchButtonText: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  availableContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 12,
    borderRadius: 8,
    marginBottom: 16,
  },
  availableLabel: {
    fontSize: 14,
  },
  availableAmount: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  inputGroup: {
    marginBottom: 12,
  },
  input: {
    borderWidth: 1,
    borderRadius: 6,
    padding: 10,
    fontSize: 14,
  },
  errorText: {
    color: colors.error,
    fontSize: 12,
    marginTop: 4,
  },
  disclaimerContainer: {
    padding: 10,
    borderRadius: 6,
    marginTop: 8,
    marginBottom: 8,
  },
  disclaimerText: {
    fontSize: 12,
    lineHeight: 16,
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: 10,
  },
  withdrawButton: {
    flex: 1,
    borderWidth: 1.5,
    borderRadius: 8,
    padding: 12,
    alignItems: 'center',
  },
  withdrawButtonText: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  cancelButton: {
    flex: 1,
    borderRadius: 8,
    padding: 12,
    alignItems: 'center',
  },
  cancelButtonText: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  processingContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    padding: 20,
    height: 200,
  },
  processingText: {
    fontSize: 16,
    fontWeight: '500',
    marginTop: 20,
  },
  processingSubtext: {
    fontSize: 14,
    marginTop: 8,
  },
  successContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    padding: 20,
    height: 200,
  },
  successIconContainer: {
    width: 70,
    height: 70,
    borderRadius: 35,
    backgroundColor: 'rgba(46, 204, 113, 0.1)',
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 16,
  },
  successText: {
    fontSize: 16,
    fontWeight: '500',
    textAlign: 'center',
    marginBottom: 8,
  },
  successSubtext: {
    fontSize: 14,
    textAlign: 'center',
  },
});