import { useState, useRef, useEffect } from "react";
import { useWindowDimensions, Platform } from "react-native";
import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
import WebView from "react-native-webview";

import { useAssets } from "expo-asset";
import * as Location from "expo-location";
import { useNavigation } from "expo-router";

import messageHandler from "./messageHandler";

export default function () {
  const [webViewKey, setWebViewKey] = useState(Math.random() * 10);
  const [assets] = useAssets([require("../assets/index.html")]);
  const [htmlString, setHtmlString] = useState<string>();
  const dimensions = useWindowDimensions();
  const webViewRef = useRef<WebView | null>();
  const navigation = useNavigation();

  const getLocation = async () => {
    const { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== "granted") return;

    const location = await Location.getCurrentPositionAsync({
      distanceInterval: 0,
      accuracy: Location.Accuracy.High,
      timeInterval: 3000,
    });

    webViewRef.current?.injectJavaScript(
      `setTimeout(() => {window.passLocation(${location.coords.longitude}, ${location.coords.latitude})}, 50); true`
    );
  };

  useEffect(() => {
    navigation.setOptions({ headerShown: false });

    return navigation.addListener("focus", () => {
      setWebViewKey(Math.random() * 10);
      getLocation();
    });
  }, [navigation]);

  useEffect(() => {
    if (assets) {
      fetch(assets[0].localUri || "")
        .then((res) => res.text())
        .then((html) => setHtmlString(html));
    }
  }, [assets]);

  if (!htmlString) return <></>;

  return (
    <SafeAreaProvider>
      <SafeAreaView
        style={{
          flex: 1,
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <WebView
          ref={webViewRef}
          injectedJavascript=""
          source={{
            html: htmlString,
          }}
          style={{
            width: dimensions.width,
            height: dimensions.height,
          }}
          scrollEnabled={false}
          overScrollMode="never"
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          scalesPageToFit={false}
          containerStyle={{
            flex: 1,
          }}
          onMessage={(event) => {
            messageHandler(event, webViewRef.current);
          }}
          webviewDebuggingEnabled={true}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          key={webViewKey}
        />
      </SafeAreaView>
    </SafeAreaProvider>
  );
}
