import React, { useState } from 'react';
import { StyleSheet, View, Text, TouchableOpacity, ScrollView, Image, Linking, Alert, Platform, Dimensions } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { LinearGradient } from 'expo-linear-gradient';
import { MessageSquare, Mail, Globe, Phone, ChevronRight, HelpCircle, BookOpen, AlertTriangle, Shield, ChevronDown, ChevronUp } from 'lucide-react-native';
import { useTheme } from '@/context/ThemeContext';
import { useRouter } from 'expo-router';
import { WebView } from 'react-native-webview';
import { Modal, Animated } from 'react-native';
import { Stack } from 'expo-router';

export default function HelpSupportScreen() {
  const { theme, colors } = useTheme();
  const router = useRouter();
  const [contactModalVisible, setContactModalVisible] = useState(false);
  const [isWebViewLoading, setIsWebViewLoading] = useState(true);
  const [modalAnimation] = useState(new Animated.Value(0));
  
  // State to track which FAQs are expanded
  const [expandedFAQs, setExpandedFAQs] = useState<Record<string, boolean>>({});
  
  // FAQ data with questions and answers
  const faqData = [
    {
      id: "deposit",
      question: "How to deposit",
      answer: "To deposit funds, go to the Trade screen and tap on the 'Deposit' button. Select your preferred payment method and follow the instructions. You can use various payment methods including bank transfers, cryptocurrency, and more depending on your location. The minimum deposit amount varies based on your region.",
      iconColor: colors.success,
      iconBg: theme === 'dark' ? 'rgba(46, 204, 113, 0.1)' : 'rgba(46, 204, 113, 0.05)'
    },
    {
      id: "withdraw",
      question: "How to withdraw",
      answer: "To withdraw funds, go to the Withdraw tab, enter the amount you wish to withdraw, select your withdrawal method, and follow the instructions. Make sure to verify your account before making your first withdrawal. Withdrawals typically process within 24-48 hours depending on the payment method and your location. There may be minimum withdrawal amounts and fees associated with certain withdrawal methods.",
      iconColor: colors.primary,
      iconBg: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)'
    },
    {
      id: "trade",
      question: "How to trade",
      answer: "To place a trade, go to the Trade screen, enter your investment amount, select a trade duration, and tap either 'Buy Up' if you think the price will rise or 'Buy Down' if you think it will fall. You can monitor your active trades in real-time and see your profit/loss as the market moves. Our platform offers various assets to trade including cryptocurrencies, forex pairs, commodities, and stocks. You can also use technical analysis tools to help make informed trading decisions.",
      iconColor: colors.accent,
      iconBg: theme === 'dark' ? 'rgba(243, 156, 18, 0.1)' : 'rgba(243, 156, 18, 0.05)'
    },
    {
      id: "verification",
      question: "Account verification",
      answer: "Account verification is not required for demo accounts. For real accounts, go to the Profile screen and tap on 'Verify Account' to complete the verification process. You'll need to provide valid identification documents such as a passport, driver's license, or national ID card. You may also need to provide proof of address and complete a facial recognition check. Verification typically takes 1-2 business days to process. Once verified, you'll have access to all platform features including deposits and withdrawals.",
      iconColor: colors.error,
      iconBg: theme === 'dark' ? 'rgba(231, 76, 60, 0.1)' : 'rgba(231, 76, 60, 0.05)'
    }
  ];
  
  // Resource data
  const resourceData = [
    {
      id: "userGuide",
      title: "User Guide",
      content: "Our comprehensive user guide covers everything you need to know about using the BATZ Trade platform. From account setup to advanced trading strategies, this guide will help you make the most of your trading experience.",
      icon: BookOpen,
      iconColor: colors.primary,
      iconBg: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)'
    },
    {
      id: "tradingTips",
      title: "Trading Tips",
      content: "Improve your trading skills with our expert tips and strategies. Learn about market analysis, risk management, and how to identify potential trading opportunities. Whether you're a beginner or experienced trader, these tips will help enhance your trading performance.",
      icon: AlertTriangle,
      iconColor: colors.success,
      iconBg: theme === 'dark' ? 'rgba(46, 204, 113, 0.1)' : 'rgba(46, 204, 113, 0.05)'
    },
    {
      id: "securityGuide",
      title: "Security Guide",
      content: "Protect your account and investments with our security best practices. Learn about two-factor authentication, secure password management, and how to recognize and avoid phishing attempts. Your security is our priority, and this guide will help you keep your account safe.",
      icon: Shield,
      iconColor: colors.error,
      iconBg: theme === 'dark' ? 'rgba(231, 76, 60, 0.1)' : 'rgba(231, 76, 60, 0.05)'
    }
  ];
  
  const handleContactSupport = () => {
    setContactModalVisible(true);
    Animated.timing(modalAnimation, {
      toValue: 1,
      duration: 300,
      useNativeDriver: Platform.OS !== 'web',
    }).start();
  };
  
  const handleCloseContactModal = () => {
    Animated.timing(modalAnimation, {
      toValue: 0,
      duration: 250,
      useNativeDriver: Platform.OS !== 'web',
    }).start(() => {
      setContactModalVisible(false);
    });
  };
  
  const toggleFAQ = (id: string) => {
    setExpandedFAQs(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };
  
  const toggleResource = (id: string) => {
    setExpandedFAQs(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };
  
  const translateY = modalAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: [Dimensions.get('window').height, 0],
  });
  
  const opacity = modalAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 1],
  });
  
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={['top']}>
      <Stack.Screen options={{ 
        title: "Help & Support",
        headerTitleStyle: { fontWeight: 'bold' }
      }} />
      
      {theme === 'dark' && (
        <LinearGradient
          colors={['rgba(30, 39, 46, 0.8)', 'rgba(0, 0, 0, 1)']}
          style={styles.backgroundGradient}
        />
      )}
      
      <ScrollView 
        style={styles.content}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.contentContainer}
      >
        <TouchableOpacity 
          style={[styles.contactCard, { backgroundColor: colors.backgroundSecondary }]}
          onPress={handleContactSupport}
        >
          <View style={styles.contactCardContent}>
            <View style={[styles.contactIconContainer, { backgroundColor: theme === 'dark' ? 'rgba(41, 171, 226, 0.1)' : 'rgba(41, 171, 226, 0.05)' }]}>
              <MessageSquare size={24} color={colors.primary} />
            </View>
            <View style={styles.contactInfo}>
              <Text style={[styles.contactTitle, { color: colors.text }]}>Contact Support</Text>
              <Text style={[styles.contactDescription, { color: colors.textSecondary }]}>
                Our team is here to help you 24/7
              </Text>
            </View>
          </View>
          <ChevronRight size={20} color={colors.textSecondary} />
        </TouchableOpacity>
        
        <View style={styles.sectionTitle}>
          <Text style={[styles.sectionTitleText, { color: colors.textSecondary }]}>Frequently Asked Questions</Text>
        </View>
        
        <View style={[styles.faqCard, { backgroundColor: colors.backgroundSecondary }]}>
          {faqData.map((faq, index) => (
            <React.Fragment key={faq.id}>
              <TouchableOpacity 
                style={styles.faqItem}
                onPress={() => toggleFAQ(faq.id)}
              >
                <View style={styles.faqItemLeft}>
                  <View style={[styles.faqIconContainer, { backgroundColor: faq.iconBg }]}>
                    <HelpCircle size={18} color={faq.iconColor} />
                  </View>
                  <Text style={[styles.faqItemText, { color: colors.text }]}>{faq.question}</Text>
                </View>
                {expandedFAQs[faq.id] ? (
                  <ChevronUp size={18} color={colors.textSecondary} />
                ) : (
                  <ChevronDown size={18} color={colors.textSecondary} />
                )}
              </TouchableOpacity>
              
              {expandedFAQs[faq.id] && (
                <View style={[
                  styles.faqExpandedContent,
                  { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.05)' }
                ]}>
                  <Text style={[styles.faqExpandedText, { color: colors.textSecondary }]}>
                    {faq.answer}
                  </Text>
                </View>
              )}
              
              {index < faqData.length - 1 && (
                <View style={[styles.divider, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)' }]} />
              )}
            </React.Fragment>
          ))}
        </View>
        
        <View style={styles.sectionTitle}>
          <Text style={[styles.sectionTitleText, { color: colors.textSecondary }]}>RESOURCES</Text>
        </View>
        
        <View style={[styles.resourcesCard, { backgroundColor: colors.backgroundSecondary }]}>
          {resourceData.map((resource, index) => (
            <React.Fragment key={resource.id}>
              <TouchableOpacity 
                style={styles.resourceItem}
                onPress={() => toggleResource(resource.id)}
              >
                <View style={styles.resourceItemLeft}>
                  <View style={[styles.resourceIconContainer, { backgroundColor: resource.iconBg }]}>
                    <resource.icon size={18} color={resource.iconColor} />
                  </View>
                  <Text style={[styles.resourceItemText, { color: colors.text }]}>{resource.title}</Text>
                </View>
                {expandedFAQs[resource.id] ? (
                  <ChevronUp size={18} color={colors.textSecondary} />
                ) : (
                  <ChevronDown size={18} color={colors.textSecondary} />
                )}
              </TouchableOpacity>
              
              {expandedFAQs[resource.id] && (
                <View style={[
                  styles.resourceExpandedContent,
                  { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.05)' }
                ]}>
                  <Text style={[styles.resourceExpandedText, { color: colors.textSecondary }]}>
                    {resource.content}
                  </Text>
                </View>
              )}
              
              {index < resourceData.length - 1 && (
                <View style={[styles.divider, { backgroundColor: theme === 'dark' ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)' }]} />
              )}
            </React.Fragment>
          ))}
        </View>
        
        <View style={styles.contactInfoSection}>
          <Text style={[styles.contactInfoTitle, { color: colors.text }]}>Contact Information</Text>
          
          <View style={styles.contactInfoItem}>
            <Mail size={16} color={colors.textSecondary} style={styles.contactInfoIcon} />
            <Text style={[styles.contactInfoText, { color: colors.textSecondary }]}>support@batztrade.com</Text>
          </View>
          
          <View style={styles.contactInfoItem}>
            <Phone size={16} color={colors.textSecondary} style={styles.contactInfoIcon} />
            <Text style={[styles.contactInfoText, { color: colors.textSecondary }]}>+1 (234) 567-8900</Text>
          </View>
          
          <View style={styles.contactInfoItem}>
            <Globe size={16} color={colors.textSecondary} style={styles.contactInfoIcon} />
            <Text style={[styles.contactInfoText, { color: colors.textSecondary }]}>www.batztrade.com</Text>
          </View>
        </View>
        
        <View style={styles.footer}>
          <Image 
            source={{ uri: 'https://cdn.prod.website-files.com/66b7dcae754fe5eef2139e69/67d2bd08bfc05787cd4dc601_THE%20BATZ%20Trade%20logo.png' }}
            style={styles.footerLogo}
            resizeMode="contain"
          />
          <Text style={[styles.footerText, { color: colors.textSecondary }]}>
            We're here to help you succeed
          </Text>
        </View>
      </ScrollView>
      
      {/* Contact Support Modal with iframe */}
      <Modal
        visible={contactModalVisible}
        transparent={true}
        animationType="none"
        onRequestClose={handleCloseContactModal}
      >
        <View style={styles.modalOverlay}>
          <Animated.View 
            style={[
              styles.modalContainer,
              { 
                transform: [{ translateY: translateY }],
                opacity: opacity,
                backgroundColor: theme === 'dark' ? colors.bgDark : colors.background
              }
            ]}
          >
            <View style={styles.modalHeader}>
              <TouchableOpacity 
                style={styles.modalCloseButton}
                onPress={handleCloseContactModal}
              >
                <ChevronDown size={24} color={colors.text} />
              </TouchableOpacity>
              <Text style={[styles.modalTitle, { color: colors.text }]}>Contact Support</Text>
              <View style={{ width: 24 }} />
            </View>
            
            {isWebViewLoading && (
              <View style={[styles.loadingContainer, { backgroundColor: theme === 'dark' ? colors.bgDark : colors.background }]}>
                <Text style={[styles.loadingText, { color: colors.textSecondary }]}>Loading...</Text>
              </View>
            )}
            
            {Platform.OS === 'web' ? (
              <iframe
                src="https://appflypolicy.emakemrnd.com.ng/contact-us.html"
                style={{
                  width: '100%',
                  height: '100%',
                  border: 'none',
                  backgroundColor: theme === 'dark' ? colors.bgDark : colors.background
                }}
                onLoad={() => setIsWebViewLoading(false)}
              />
            ) : (
              <WebView
                source={{ uri: "https://appflypolicy.emakemrnd.com.ng/contact-us.html" }}
                style={styles.webView}
                onLoad={() => setIsWebViewLoading(false)}
                onError={(syntheticEvent) => {
                  const { nativeEvent } = syntheticEvent;
                  console.error('WebView error: ', nativeEvent);
                  Alert.alert(
                    "Connection Error",
                    "Failed to load contact form. Please try again later.",
                    [
                      { text: "Close", onPress: handleCloseContactModal }
                    ]
                  );
                }}
              />
            )}
          </Animated.View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  backgroundGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  content: {
    flex: 1,
  },
  contentContainer: {
    padding: 16,
    paddingBottom: 32,
  },
  contactCard: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
    borderRadius: 12,
    marginBottom: 24,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  contactCardContent: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  contactIconContainer: {
    width: 48,
    height: 48,
    borderRadius: 24,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  contactInfo: {
    flex: 1,
  },
  contactTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 2,
  },
  contactDescription: {
    fontSize: 12,
  },
  sectionTitle: {
    marginBottom: 8,
  },
  sectionTitleText: {
    fontSize: 14,
    fontWeight: '500',
    textTransform: 'uppercase',
  },
  faqCard: {
    borderRadius: 12,
    marginBottom: 24,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    overflow: 'hidden',
  },
  faqItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  faqItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  faqIconContainer: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  faqItemText: {
    fontSize: 15,
    fontWeight: '500',
  },
  faqExpandedContent: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    paddingLeft: 64, // Align with the text above
  },
  faqExpandedText: {
    fontSize: 14,
    lineHeight: 20,
  },
  divider: {
    height: 1,
    marginHorizontal: 16,
  },
  resourcesCard: {
    borderRadius: 12,
    marginBottom: 24,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    overflow: 'hidden',
  },
  resourceItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  resourceItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  resourceIconContainer: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  resourceItemText: {
    fontSize: 15,
    fontWeight: '500',
  },
  resourceExpandedContent: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    paddingLeft: 64, // Align with the text above
  },
  resourceExpandedText: {
    fontSize: 14,
    lineHeight: 20,
  },
  contactInfoSection: {
    marginBottom: 24,
  },
  contactInfoTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 12,
  },
  contactInfoItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  contactInfoIcon: {
    marginRight: 8,
  },
  contactInfoText: {
    fontSize: 14,
  },
  footer: {
    alignItems: 'center',
  },
  footerLogo: {
    width: 100,
    height: 40,
    marginBottom: 8,
  },
  footerText: {
    fontSize: 12,
    textAlign: 'center',
  },
  // Modal styles
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    borderRadius: Platform.OS === 'ios' ? 20 : 0,
    overflow: 'hidden',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 10,
    elevation: 5,
  },
  modalHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0, 0, 0, 0.1)',
  },
  modalCloseButton: {
    padding: 8,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  webView: {
    flex: 1,
  },
  loadingContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 10,
  },
  loadingText: {
    fontSize: 16,
  },
});