import { useCurrentTrain } from "@/stateBox/useCurrentTrain";
import { AppState, InteractionManager, View } from "react-native";
import {
  activateKeepAwakeAsync,
  deactivateKeepAwake,
} from "expo-keep-awake";
import { FixedTrain } from "./FixedPositionBox/FixedTrainBox";
import { FixedStation } from "./FixedPositionBox/FixedStationBox";
import { FixedNearestStationBox } from "./FixedPositionBox/FixedNearestStationBox";
import { useEffect } from "react";
import { useTrainMenu } from "@/stateBox/useTrainMenu";
import { useSafeAreaInsets } from "react-native-safe-area-context";

const KEEP_AWAKE_TAG = "fixed-position-box";

const isActivityUnavailableError = (error: unknown) =>
  String(error).includes("The current activity is no longer available");

export const FixedPositionBox = () => {
  const { mapSwitch } = useTrainMenu();
  const { fixedPosition, fixedPositionSize, setFixedPositionSize } =
    useCurrentTrain();
  const { top } = useSafeAreaInsets();
  useEffect(() => {
    setFixedPositionSize(mapSwitch == "true" ? 76 : 80);
  }, [mapSwitch]);

  useEffect(() => {
    if (__DEV__) {
      return;
    }

    let mounted = true;
    let timerId: ReturnType<typeof setTimeout> | null = null;

    const activate = async () => {
      if (!mounted || AppState.currentState !== "active") {
        return;
      }

      try {
        await activateKeepAwakeAsync(KEEP_AWAKE_TAG);
      } catch (error) {
        if (!isActivityUnavailableError(error)) {
          console.warn("Failed to activate keep awake", error);
        }
      }
    };

    const interactionHandle = InteractionManager.runAfterInteractions(() => {
      timerId = setTimeout(() => {
        void activate();
      }, 250);
    });

    const subscription = AppState.addEventListener("change", (state) => {
      if (state === "active") {
        timerId = setTimeout(() => {
          void activate();
        }, 250);
        return;
      }

      deactivateKeepAwake(KEEP_AWAKE_TAG).catch(() => {});
    });

    return () => {
      mounted = false;
      if (timerId) {
        clearTimeout(timerId);
      }
      interactionHandle.cancel();
      subscription.remove();
      deactivateKeepAwake(KEEP_AWAKE_TAG).catch(() => {});
    };
  }, []);

  return (
    <View
      style={{
        position: "absolute",
        top,
        borderRadius: 5,
        zIndex: 1500,
        width: "100%",
        height: fixedPositionSize,
        flexDirection: "row",
      }}
      pointerEvents="box-none"
    >
      {fixedPosition.type === "station" && (
        <FixedStation stationID={fixedPosition.value} />
      )}
      {fixedPosition.type === "train" && (
        <FixedTrain trainID={fixedPosition.value} />
      )}
      {fixedPosition.type === "nearestStation" && (
        <FixedNearestStationBox />
      )}
    </View>
  );
};
