import { useEffect, useReducer } from "react";
import { AppState, AppStateStatus } from "react-native";
import {ContentBlock} from "./typings";
import CfCore from "./CfCore";

type Action =
  | { type: "state"; state: AppStateStatus }
  | { type: "page"; pathName: string };

type PageState = {
  lastPage: string;
  nextPage: string;
  timestamp: number;
  previousTimestamp: number;
};


const stateTimesReducer = (state: PageState, action: Action) => {
  const newState = { ...state };

  switch (action.type) {
    case "state":
      if (action.state === "background") {
        newState.previousTimestamp = newState.timestamp;
        newState.timestamp = Date.now();
        newState.lastPage = newState.nextPage;
        //newState.nextPage = "";  // commented -> assuming that page after background
                                   // will be the same as before
      } else {
        newState.timestamp = Date.now();
        newState.previousTimestamp = 0;
      }
      break;

    case "page":
      newState.lastPage = newState.nextPage;
      newState.nextPage = action.pathName;

      const ts = newState.timestamp;
      newState.timestamp = Date.now();
      newState.previousTimestamp = ts;
      break;
  }

  return newState;
};

const usePageTracking = (contentBlock: ContentBlock, appPath: string) => {
  const [stateTimes, dispatchStateTimes] = useReducer(stateTimesReducer, {
    lastPage: "",
    nextPage: "",
    timestamp: 0,
    previousTimestamp: 0,
  });

  useEffect(() => {
    const handleAppStateChange = (nextAppState: AppStateStatus) => {
      dispatchStateTimes({ type: "state", state: nextAppState });
    };

    const subscription = AppState.addEventListener(
      "change",
      handleAppStateChange
    );

    return () => {
      subscription.remove();
    };
  }, []);

  useEffect(() => {
    const MIN_DURATION_THRESHOLD = 1;

    if (!stateTimes.previousTimestamp) {
      return;
    }

    const duration =
      (stateTimes.timestamp - stateTimes.previousTimestamp) / 1000;

    if (duration < MIN_DURATION_THRESHOLD) {
      return;
    }

    if (stateTimes.lastPage.trim() === "") {
      return;
    }


    let pageProperties = {
      content_block: contentBlock,
      page_path: appPath,
      page_title: stateTimes.lastPage,
      duration: parseFloat(duration.toFixed(2)),
      render_time: 0
    }
    CfCore.logPageEvent(pageProperties)

  }, [stateTimes]);

  return {
    dispatchStateTimes,
  };
};

export default usePageTracking;
