import React, { useState, useRef } from 'react';
import { View, Text, ActivityIndicator, TouchableOpacity, SafeAreaView, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';
import { StatusBar } from 'expo-status-bar';

export const WebViewScreen: React.FC = () => {
  const [isInitialLoad, setIsInitialLoad] = useState(true);
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);
  const webViewRef = useRef<WebView>(null);

  const handleRetry = () => {
    setHasError(false);
    setIsLoading(true);
    setIsInitialLoad(true);
    if (webViewRef.current) {
      webViewRef.current.reload();
    }
  };

  // Inject JavaScript to prevent links from opening in a new tab/window
  const preventNewWindowJS = `
    (function() {
      // Overwrite window.open to force same-window navigation
      window.open = function(url) {
        window.location.href = url;
        return null;
      };
      
      // Convert all target="_blank" links to target="_self" dynamically
      document.addEventListener('click', function(e) {
        var target = e.target.closest('a');
        if (target && target.target === '_blank') {
          target.target = '_self';
        }
      }, true);
    })();
    true;
  `;

  return (
    <SafeAreaView className="flex-1 bg-[#0F172A]" style={styles.safeArea}>
      <StatusBar style="light" backgroundColor="#0F172A" />

      {/* Main WebView Component */}
      <WebView
        ref={webViewRef}
        source={{ uri: 'https://poskasir.my.id/app/login' }}
        className="flex-1"
        domStorageEnabled={true}
        javaScriptEnabled={true}
        allowsBackForwardNavigationGestures={true}
        setSupportMultipleWindows={false} // Force Android new windows to open in-place
        injectedJavaScript={preventNewWindowJS} // Convert links in iOS/Android
        showsVerticalScrollIndicator={false}
        showsHorizontalScrollIndicator={false}
        onLoadStart={() => {
          setIsLoading(true);
          setHasError(false);
        }}
        onLoadEnd={() => {
          setIsLoading(false);
          setIsInitialLoad(false);
        }}
        onError={() => {
          setHasError(true);
          setIsLoading(false);
          setIsInitialLoad(false);
        }}
        style={hasError ? { display: 'none' } : { flex: 1 }}
      />

      {/* Premium Full-Screen Glassmorphic Loading Indicator */}
      {isInitialLoad && (
        <View style={StyleSheet.absoluteFillObject} className="bg-[#0F172A] items-center justify-center z-50">
          <View className="bg-white/10 p-8 rounded-3xl items-center border border-white/15 shadow-2xl backdrop-blur-md">
            <ActivityIndicator size="large" color="#3B82F6" />
            <Text className="text-white font-extrabold text-base mt-4 text-center tracking-tight font-heading">
              POS Kasir
            </Text>
            <Text className="text-blue-200/70 text-[10px] font-bold mt-1 text-center uppercase tracking-wider">
              Memuat Antarmuka Premium...
            </Text>
          </View>
        </View>
      )}

      {/* Offline Error Fallback Screen */}
      {hasError && (
        <View style={StyleSheet.absoluteFillObject} className="bg-[#0F172A] items-center justify-center p-6 z-50">
          <View className="bg-white/5 border border-white/10 rounded-3xl p-6 w-full max-w-sm items-center shadow-2xl">
            {/* Visual Icon */}
            <View className="w-16 h-16 bg-red-500/10 rounded-full items-center justify-center border border-red-500/20 mb-4">
              <Text className="text-3xl">📶</Text>
            </View>

            <Text className="text-white font-black text-lg text-center tracking-tight">
              Koneksi Terputus
            </Text>
            
            <Text className="text-slate-400 text-xs text-center mt-2.5 leading-relaxed font-semibold">
              Tidak dapat terhubung ke server POS Kasir. Pastikan HP abang terhubung ke internet (Wi-Fi/Data Seluler) lalu ketuk tombol coba lagi.
            </Text>

            {/* Retry Button */}
            <TouchableOpacity
              onPress={handleRetry}
              className="mt-6 w-full bg-blue-600 active:bg-blue-700 py-3.5 rounded-2xl items-center shadow-lg shadow-blue-500/20"
            >
              <Text className="text-white font-black text-sm uppercase tracking-wider">
                Coba Lagi 🔄
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      )}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  safeArea: {
    paddingTop: StatusBar.currentHeight || 0,
  },
});
