// src/components/HiddenDevMenu/index.tsx
import React, { useState, useRef } from 'react';
import {
  View,
  Modal,
  TouchableOpacity,
  Dimensions,
  SafeAreaView,
  GestureResponderEvent
} from 'react-native';
import { ThemedText } from '../ThemedText';
import Settings from '../../modules/core/settings';
import { styles } from './styles';

interface HiddenDevMenuProps {
  children: React.ReactNode;
}

const HiddenDevMenu: React.FC<HiddenDevMenuProps> = ({ children }) => {
  const [isDevMenuVisible, setIsDevMenuVisible] = useState(false);
  const [gestureMode, setGestureMode] = useState(false);
  const [leftTaps, setLeftTaps] = useState(0);
  const [rightTaps, setRightTaps] = useState(0);
  const [showDebugInfo, setShowDebugInfo] = useState(false);
  
  // Get screen dimensions
  const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
  
  // Gesture zone settings - very narrow edge zones
  const edgeZoneWidth = 16; // Width of left/right zones (just the padding area)
  const edgeZoneHeight = 120; // Height of zones
  
  // Refs for timeouts
  const gestureModeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const sequenceTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Reset gesture mode
  const resetGestureMode = () => {
    setGestureMode(false);
    setLeftTaps(0);
    setRightTaps(0);
    
    if (gestureModeTimeoutRef.current) {
      clearTimeout(gestureModeTimeoutRef.current);
    }
    if (sequenceTimeoutRef.current) {
      clearTimeout(sequenceTimeoutRef.current);
    }
  };

  // Activate gesture mode for 3 seconds
  const activateGestureMode = () => {
    setGestureMode(true);
    setLeftTaps(0);
    setRightTaps(0);
    
    if (showDebugInfo) {
      console.log('Gesture mode activated');
    }

    // Clear existing timeout
    if (gestureModeTimeoutRef.current) {
      clearTimeout(gestureModeTimeoutRef.current);
    }

    // Set 3-second timeout
    gestureModeTimeoutRef.current = setTimeout(() => {
      resetGestureMode();
      if (showDebugInfo) {
        console.log('Gesture mode timeout');
      }
    }, 3000);
  };

  // Handle dead taps (taps that don't hit interactive elements)
  const handleBackgroundTap = (event: GestureResponderEvent) => {
    // Only activate gesture mode if we're not already in it
    if (!gestureMode) {
      activateGestureMode();
    }
  };

  // Handle left edge taps
  const handleLeftTap = () => {
    if (!gestureMode) return;

    const newLeftTaps = leftTaps + 1;
    setLeftTaps(newLeftTaps);
    
    if (showDebugInfo) {
      console.log(`Left taps: ${newLeftTaps}`);
    }

    // Clear ALL existing timeouts and reset the main 3-second timer
    if (gestureModeTimeoutRef.current) {
      clearTimeout(gestureModeTimeoutRef.current);
    }
    if (sequenceTimeoutRef.current) {
      clearTimeout(sequenceTimeoutRef.current);
    }

    // Reset the main 3-second gesture mode timeout
    gestureModeTimeoutRef.current = setTimeout(() => {
      resetGestureMode();
      if (showDebugInfo) {
        console.log('Gesture mode timeout after left tap');
      }
    }, 3000);

    // Check if we completed left sequence
    if (newLeftTaps >= 3) {
      if (showDebugInfo) {
        console.log('Left sequence complete, waiting for right taps...');
      }
    }
  };

  // Handle right edge taps
  const handleRightTap = () => {
    if (!gestureMode || leftTaps < 3) return;

    const newRightTaps = rightTaps + 1;
    setRightTaps(newRightTaps);
    
    if (showDebugInfo) {
      console.log(`Right taps: ${newRightTaps}`);
    }

    // Clear ALL existing timeouts and reset the main 3-second timer
    if (gestureModeTimeoutRef.current) {
      clearTimeout(gestureModeTimeoutRef.current);
    }
    if (sequenceTimeoutRef.current) {
      clearTimeout(sequenceTimeoutRef.current);
    }

    // Check if sequence is complete
    if (newRightTaps >= 3) {
      if (showDebugInfo) {
        console.log('Sequence complete! Opening dev menu...');
      }
      setIsDevMenuVisible(true);
      resetGestureMode();
    } else {
      // Reset the main 3-second gesture mode timeout
      gestureModeTimeoutRef.current = setTimeout(() => {
        resetGestureMode();
        if (showDebugInfo) {
          console.log('Gesture mode timeout after right tap');
        }
      }, 3000);
    }
  };

  const closeDevMenu = () => {
    setIsDevMenuVisible(false);
  };

  return (
    <View style={styles.container}>
      {/* Main app content - no touch interference */}
      {children}
      
      {/* Larger activation zones - top corners for manual gesture mode activation */}
      {!gestureMode && (
        <>
          <TouchableOpacity
            style={[
              styles.activationZone, 
              styles.topLeftActivation,
              showDebugInfo && styles.debugActivationZone
            ]}
            onLongPress={activateGestureMode}
            delayLongPress={800} // Reduced from 1000ms to 800ms
            activeOpacity={1}
          />
          <TouchableOpacity
            style={[
              styles.activationZone, 
              styles.topRightActivation,
              showDebugInfo && styles.debugActivationZone
            ]}
            onLongPress={activateGestureMode}
            delayLongPress={800} // Reduced from 1000ms to 800ms
            activeOpacity={1}
          />
        </>
      )}
      
      {/* Left gesture zone - only visible when gesture mode is active */}
      {gestureMode && (
        <TouchableOpacity
          style={[
            styles.gestureZone,
            styles.leftZone,
            {
              top: (screenHeight - edgeZoneHeight) / 2,
              width: edgeZoneWidth,
              height: edgeZoneHeight,
              backgroundColor: showDebugInfo ? 'rgba(255, 0, 0, 0.3)' : 'transparent',
            }
          ]}
          onPress={handleLeftTap}
          activeOpacity={0.7}
        />
      )}
      
      {/* Right gesture zone - only visible when gesture mode is active */}
      {gestureMode && (
        <TouchableOpacity
          style={[
            styles.gestureZone,
            styles.rightZone,
            {
              top: (screenHeight - edgeZoneHeight) / 2,
              width: edgeZoneWidth,
              height: edgeZoneHeight,
              backgroundColor: showDebugInfo ? 'rgba(0, 255, 0, 0.3)' : 'transparent',
            }
          ]}
          onPress={handleRightTap}
          activeOpacity={0.7}
        />
      )}

      {/* Debug indicator */}
      {gestureMode && showDebugInfo && (
        <View style={styles.debugIndicator}>
          <ThemedText variant="caption" style={styles.debugText}>
            Gesture Mode: L:{leftTaps}/3 R:{rightTaps}/3
          </ThemedText>
        </View>
      )}

      {/* Developer Menu Modal */}
      <Modal
        visible={isDevMenuVisible}
        transparent={false}
        presentationStyle="pageSheet"
        animationType="slide"
        onRequestClose={closeDevMenu}
      >
        <SafeAreaView style={styles.modalContainer}>
          <Settings 
            onClose={closeDevMenu}
            showDebugInfo={showDebugInfo}
            onToggleDebug={setShowDebugInfo}
          />
        </SafeAreaView>
      </Modal>
    </View>
  );
};

export default HiddenDevMenu;