import * as React from 'react';
import { WebView } from 'react-native-webview';
import { Linking,BackHandler, View, Text, StyleSheet,ActivityIndicator } from 'react-native';
import UriBuilderService from '../services/UriBuilderService';
import { UserService } from '../services/UserService';
import { RateLimitService } from '../services/RatelimitService';
import NetInfo from '@react-native-community/netinfo';


export function MCOfferwallView({ adunitId }: { adunitId: string }) {

  //about:blank url will break compilation on ios
  const [currentUrl, setCurrentUrl] = React.useState<string>(''); // State for the current URL
  const [isConnected, setIsConnected] = React.useState<boolean>(true);
  const [isLoading, setIsLoading] = React.useState(true);
  const mychipsDomain = 'mychips.io';
  const webViewRef = React.useRef<WebView>(null);
  const currentUrlRef = React.useRef(currentUrl); // Ref to keep track of the current URL



  

  const getUserData = async () => {
    const userService = new UserService();
    const userId = await userService.getOrCreateId();
    const advertisingId = await userService.getAdvertisingId();
    const age = await userService.getAge();
    const gender = await userService.getGender();
    const totalVirtualCurrency = await userService.getCurrentTotalCurrency();
    return { userId, advertisingId, age, gender, totalVirtualCurrency };
  };

  const buildUrl = async () => {
    const userData = await getUserData();
    const uriBuilderService = new UriBuilderService();
    return uriBuilderService.buildOfferwallUrl(
      adunitId,
      userData.userId,
      userData.advertisingId,
      userData.gender,
      userData.age,
      userData.totalVirtualCurrency
    );
  };

  const fetchUserDataAndBuildUrl = async () => {
    try {
      const url = await buildUrl();
      setCurrentUrl(url);
    } catch (error) {
      console.error('Failed to build offerwall URL', error); 
    }
  };

  ///get the current navigation url and keep it updated
  const onNavigationStateChange = (navState: any) => {
    const { url } = navState;
    if (url !== currentUrl) {
      setCurrentUrl(url); // Update the state with the new URL
      currentUrlRef.current = url;
      console.log("onNavigationStateChange:"+url); 
      
    }

  };

  ///handle logic for specific link
  const onShouldStartLoadWithRequest = (request: any) => {
    const { url } = request;
    
    console.log("onShouldStartLoadWithRequest:" + url);

    if (url.includes('blank') || url.includes('file:') ) 
    {
      return false;
    }

    if (url.includes('/redirect')) {
      Linking.openURL(url).catch((err) => console.error("Couldn't load page", err));
      return false; // Prevent the WebView from loading the URL
    }
    if(url.includes('mychips://')){
      return false;
    } 

    return true; // Allow the WebView to load the URL
  };

  const onLoadStart = () => {
    //console.log("WebView Load Started");
  };

  const onLoad = () => {
    //console.log("WebView Loaded");
  };

  const onLoadEnd = () => {
    if(currentUrl=='' || currentUrl=='about:blank'){
      fetchUserDataAndBuildUrl();
      console.log("onLoadEnd: fetchUserDataAndBuildUrl");
    }
    console.log("WebView Load Ended" );
    
    if(isLoading && currentUrl.includes(mychipsDomain)){
      setIsLoading(false);
    }
  };

  const onError = (error:any) => {
    console.error("WebView Error: ", error);
  };

  //handle navigation logic
  const onBackPress = () => {
    const url = currentUrlRef.current; // Use 

    if (url.includes('page=home') || !url.includes('page=')) {
      return false; // Allow default back button behavior if URL contains 'page=home'
    } else {
      webViewRef.current?.goBack();
      return true; // Prevent default back button behavior
    }
  };

 

  React.useEffect(() => {
    RateLimitService.enableRequest();

    setTimeout(() => {
      if(currentUrlRef.current == 'about:blank' || currentUrlRef.current == ''){
        fetchUserDataAndBuildUrl();
        console.log("01"); 
      }
     }, 1000); // Delay to ensure WebView is ready
     
     setTimeout(() => {
      if(isLoading)
        setIsLoading(false);
     },5000)

    const unsubscribeNetInfo  = NetInfo.addEventListener((state: any) => {
      setIsConnected(state.isConnected);
      
    });

    BackHandler.addEventListener('hardwareBackPress', onBackPress);
    return () => {
      BackHandler.removeEventListener('hardwareBackPress', onBackPress);
      unsubscribeNetInfo ()
    };
  }, []);

  return (
    <View style={{ flex: 1 }}>
   
    <WebView
     // key={currentUrl} // Use URL as key to force re-render
      ref={webViewRef}
      source={{ uri: currentUrl }}
      onNavigationStateChange={onNavigationStateChange}
      onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
      onLoadStart={onLoadStart}
      onLoad={onLoad}
      onLoadEnd={onLoadEnd}
      onError={onError}
    />
    {isLoading && (
      <View style={styles.loaderContainer}>
        <ActivityIndicator size="large" style={styles.loader} />
      </View>
    )}
    {!isConnected && (
      <View style={styles.offlineContainer}>
        <Text style={styles.offlineText}>No Internet Connection</Text>
      </View>
    )}
  
  </View>
  );
}


const styles = StyleSheet.create({
  offlineContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#b52424',
    zIndex: 1, // Ensure the offline message is on top
  },
  offlineText: {
    color: '#fff',
  },
  loaderContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    width: '100%',
    height: '100%',
    zIndex: 1, // Ensures loader is above other content
    backgroundColor: 'rgba(255, 255, 255, 0.8)', // Optional: Adds a semi-transparent background
  },
  loader: {
    // Additional styles if needed
  },
});