import React, { useState, useEffect, useRef } from 'react';
import { Modal, View, Text, StyleSheet, TouchableOpacity, ActivityIndicator, Platform, Animated, Easing } from 'react-native';
import { useTheme } from '@/context/ThemeContext';
import { WifiOff, RefreshCw, AlertTriangle, Wifi } from 'lucide-react-native';
import { LinearGradient } from 'expo-linear-gradient';

interface ConnectionErrorModalProps {
  visible: boolean;
  onRetry: () => void;
}

export default function ConnectionErrorModal({ visible, onRetry }: ConnectionErrorModalProps) {
  const { theme, colors } = useTheme();
  const [isRetrying, setIsRetrying] = useState(false);
  const [retryCount, setRetryCount] = useState(0);
  const [showAdvancedInfo, setShowAdvancedInfo] = useState(false);
  
  // Animation values
  const scaleAnim = useRef(new Animated.Value(0.9)).current;
  const opacityAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(Platform.OS === 'web' ? 0 : 50)).current;
  
  // Reset retry state when modal visibility changes
  useEffect(() => {
    if (!visible) {
      setIsRetrying(false);
      
      // Reset animations
      scaleAnim.setValue(0.9);
      opacityAnim.setValue(0);
      slideAnim.setValue(Platform.OS === 'web' ? 0 : 50);
    } else {
      // Animate in
      Animated.parallel([
        Animated.timing(scaleAnim, {
          toValue: 1,
          duration: 400,
          useNativeDriver: Platform.OS !== 'web',
          easing: Easing.out(Easing.back(1.2)),
        }),
        Animated.timing(opacityAnim, {
          toValue: 1,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
        Animated.timing(slideAnim, {
          toValue: 0,
          duration: 300,
          useNativeDriver: Platform.OS !== 'web',
        }),
      ]).start();
    }
  }, [visible]);
  
  const handleRetry = () => {
    setIsRetrying(true);
    setRetryCount(prev => prev + 1);
    
    // Simulate retry process
    setTimeout(() => {
      onRetry();
      setIsRetrying(false);
    }, 2000);
  };
  
  // Determine error message based on retry count
  const getErrorMessage = () => {
    if (retryCount === 0) {
      return "Your internet connection appears to be offline. Please check your network settings.";
    } else if (retryCount === 1) {
      return "Still having trouble connecting. Please ensure your device has internet access.";
    } else if (retryCount === 2) {
      return "Connection issues persist. This could be due to network restrictions or service provider issues.";
    } else {
      return "We're experiencing technical difficulties connecting to the internet. Please check your network settings or try again later.";
    }
  };
  
  return (
    <Modal
      visible={visible}
      transparent={true}
      animationType="none"
    >
      <View style={styles.modalOverlay}>
        <Animated.View 
          style={[
            styles.modalContainer,
            { 
              backgroundColor: theme === 'dark' ? colors.backgroundSecondary : colors.background,
              opacity: opacityAnim,
              transform: Platform.OS === 'web' 
                ? [{ scale: scaleAnim }] 
                : [{ scale: scaleAnim }, { translateY: slideAnim }]
            }
          ]}
        >
          {theme === 'dark' && (
            <LinearGradient
              colors={['rgba(30, 39, 46, 0.8)', 'rgba(30, 39, 46, 0.5)']}
              style={styles.modalGradient}
            />
          )}
          
          <View style={styles.iconContainer}>
            <WifiOff size={40} color={colors.error} />
          </View>
          
          <Text style={[styles.title, { color: colors.text }]}>No Internet Connection</Text>
          
          <Text style={[styles.message, { color: colors.textSecondary }]}>
            {getErrorMessage()}
          </Text>
          
          {showAdvancedInfo && (
            <View style={[
              styles.advancedInfoContainer,
              { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.05)' }
            ]}>
              <Text style={[styles.advancedInfoTitle, { color: colors.text }]}>
                Troubleshooting Tips
              </Text>
              <Text style={[styles.advancedInfoText, { color: colors.textSecondary }]}>
                • Check if your device is in airplane mode
              </Text>
              <Text style={[styles.advancedInfoText, { color: colors.textSecondary }]}>
                • Try connecting to a different Wi-Fi network
              </Text>
              <Text style={[styles.advancedInfoText, { color: colors.textSecondary }]}>
                • Check if your mobile data is enabled
              </Text>
              <Text style={[styles.advancedInfoText, { color: colors.textSecondary }]}>
                • Restart your router if you're on Wi-Fi
              </Text>
            </View>
          )}
          
          <TouchableOpacity
            style={[styles.retryButton, { backgroundColor: colors.primary }]}
            onPress={handleRetry}
            disabled={isRetrying}
          >
            {isRetrying ? (
              <ActivityIndicator color="#FFFFFF" size="small" />
            ) : (
              <>
                <RefreshCw size={16} color="#FFFFFF" />
                <Text style={styles.retryButtonText}>Retry Connection</Text>
              </>
            )}
          </TouchableOpacity>
          
          <TouchableOpacity
            style={styles.advancedButton}
            onPress={() => setShowAdvancedInfo(!showAdvancedInfo)}
          >
            {showAdvancedInfo ? (
              <Text style={[styles.advancedButtonText, { color: colors.primary }]}>
                Hide Troubleshooting Tips
              </Text>
            ) : (
              <Text style={[styles.advancedButtonText, { color: colors.primary }]}>
                Show Troubleshooting Tips
              </Text>
            )}
          </TouchableOpacity>
          
          <View style={styles.tipContainer}>
            <AlertTriangle size={14} color={colors.accent} />
            <Text style={[styles.tipText, { color: colors.textSecondary }]}>
              You can continue using the app once your internet connection is restored.
            </Text>
          </View>
          
          <View style={[
            styles.statusContainer,
            { backgroundColor: theme === 'dark' ? 'rgba(0, 0, 0, 0.2)' : 'rgba(0, 0, 0, 0.05)' }
          ]}>
            <Wifi size={14} color={colors.textSecondary} />
            <Text style={[styles.statusText, { color: colors.textSecondary }]}>
              {isRetrying ? "Checking connection..." : "Waiting for connection..."}
            </Text>
          </View>
        </Animated.View>
      </View>
    </Modal>
  );
}

const styles = StyleSheet.create({
  modalOverlay: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    padding: 20,
  },
  modalContainer: {
    width: '100%',
    maxWidth: 400,
    borderRadius: 16,
    padding: 24,
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 5,
    position: 'relative',
    overflow: 'hidden',
  },
  modalGradient: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  iconContainer: {
    marginBottom: 16,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 12,
    textAlign: 'center',
  },
  message: {
    fontSize: 14,
    marginBottom: 24,
    textAlign: 'center',
    lineHeight: 20,
  },
  retryButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    paddingHorizontal: 24,
    borderRadius: 12,
    width: '100%',
    marginBottom: 12,
  },
  retryButtonText: {
    color: '#FFFFFF',
    fontWeight: 'bold',
    marginLeft: 8,
  },
  advancedButton: {
    paddingVertical: 8,
  },
  advancedButtonText: {
    fontSize: 14,
  },
  advancedInfoContainer: {
    width: '100%',
    padding: 12,
    borderRadius: 8,
    marginBottom: 16,
  },
  advancedInfoTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  advancedInfoText: {
    fontSize: 12,
    marginBottom: 4,
  },
  tipContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 16,
    marginBottom: 8,
  },
  tipText: {
    fontSize: 12,
    marginLeft: 6,
  },
  statusContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
    paddingHorizontal: 12,
    borderRadius: 16,
    marginTop: 8,
  },
  statusText: {
    fontSize: 12,
    marginLeft: 6,
  },
});