import { useEffect, useState } from "react";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { useDataContext } from "../../common/contexts/data_context";
import { useGetRoute } from "./useGetRoute";
import { router } from "expo-router";

export const usePreviewRoute = (routeId: number) => {
  const { requestStatus, route } = useGetRoute(routeId);
  const { routeRepository } = useDataContext();
  const [requestStatusSave, setRequestStatusSave] = useState<ApiRequestStatus>(
    ApiRequestStatus.IDLE
  );
  const [mainRequestStatus, setMainRequestStatus] = useState<ApiRequestStatus>(
    ApiRequestStatus.IDLE
  );

  useEffect(() => {
    const requests = [requestStatus, requestStatusSave];
    if (requests.every((request) => request === ApiRequestStatus.SUCCESS)) {
      setMainRequestStatus(ApiRequestStatus.SUCCESS);
    } else if (requests.some((request) => request === ApiRequestStatus.ERROR)) {
      setMainRequestStatus(ApiRequestStatus.ERROR);
    } else if (
      requests.some((request) => request === ApiRequestStatus.LOADING)
    ) {
      setMainRequestStatus(ApiRequestStatus.LOADING);
    } else {
      setMainRequestStatus(ApiRequestStatus.IDLE);
    }
  }, [requestStatus, requestStatusSave]);

  const saveRoute = async () => {
    setRequestStatusSave(ApiRequestStatus.LOADING);
    try {
      await routeRepository!.saveRoute(routeId);
      router.dismissAll();
    } catch (error) {
      setRequestStatusSave(ApiRequestStatus.ERROR);
    }
  };

  return { mainRequestStatus, saveRoute, route };
};
