import React, { useRef } from 'react';
import { View, StyleSheet, SafeAreaView } from 'react-native';
import { WebView, WebViewMessageEvent } from 'react-native-webview';
import { useRouter } from 'expo-router';
import { AppColors } from '@/constants/theme';

// Remote URL for the test page (loaded from server)
// Add cache-busting query param to force reload
const TEST_PAGE_URL = `https://wellnuo.smartlaunchhub.com/test-bridge.html?v=${Date.now()}`;

export default function BugScreen() {
  const router = useRouter();
  const webViewRef = useRef<WebView>(null);

  // Handle messages from WebView
  const handleMessage = (event: WebViewMessageEvent) => {
    try {
      const data = JSON.parse(event.nativeEvent.data);
      console.log('[Bug WebView] Received message:', data);

      switch (data.action) {
        case 'NAVIGATE':
          handleNavigation(data.screen);
          break;
        case 'NATIVE_FEATURE':
          handleNativeFeature(data.feature);
          break;
        case 'CUSTOM':
          handleCustomMessage(data.payload);
          break;
        default:
          console.log('[Bug WebView] Unknown action:', data.action);
      }
    } catch (error) {
      console.error('[Bug WebView] Error parsing message:', error);
    }
  };

  // Navigate to different screens
  const handleNavigation = (screen: string) => {
    console.log('[Bug WebView] Navigating to:', screen);

    switch (screen) {
      case 'beneficiaries':
        router.push('/(tabs)/');
        break;
      case 'chat':
        router.push('/(tabs)/chat');
        break;
      case 'profile':
        router.push('/(tabs)/profile');
        break;
      default:
        console.log('[Bug WebView] Unknown screen:', screen);
        // Send error back to WebView
        sendToWebView({ error: `Unknown screen: ${screen}` });
    }
  };

  // Handle native feature requests
  const handleNativeFeature = (feature: string) => {
    console.log('[Bug WebView] Native feature requested:', feature);

    switch (feature) {
      case 'bluetooth':
        // TODO: Implement Bluetooth scanning screen
        sendToWebView({
          status: 'not_implemented',
          message: 'Bluetooth scanning will be implemented here'
        });
        break;
      case 'camera':
        // TODO: Implement camera
        sendToWebView({
          status: 'not_implemented',
          message: 'Camera will be implemented here'
        });
        break;
      default:
        sendToWebView({ error: `Unknown feature: ${feature}` });
    }
  };

  // Handle custom messages
  const handleCustomMessage = (payload: any) => {
    console.log('[Bug WebView] Custom message:', payload);

    // Echo back with confirmation
    sendToWebView({
      status: 'received',
      echo: payload,
      processedAt: Date.now()
    });
  };

  // Send message TO WebView
  const sendToWebView = (data: object) => {
    const script = `
      window.dispatchEvent(new MessageEvent('message', {
        data: '${JSON.stringify(data)}'
      }));
      true;
    `;
    webViewRef.current?.injectJavaScript(script);
  };

  return (
    <SafeAreaView style={styles.container}>
      <WebView
        ref={webViewRef}
        source={{ uri: TEST_PAGE_URL }}
        style={styles.webview}
        onMessage={handleMessage}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        startInLoadingState={true}
        scalesPageToFit={true}
        cacheEnabled={false}
        incognito={true}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.background,
  },
  webview: {
    flex: 1,
  },
});
