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

export const useRankActivity = (activityId: number) => {
  const { activityRepository } = useDataContext();
  const [requestStatus, setRequestStatus] = useState<ApiRequestStatus>(
    ApiRequestStatus.IDLE
  );
  const [ratingModal, setRatingModal] = useState<boolean>(false);

  const setLoading = async () => {
    setRequestStatus(ApiRequestStatus.LOADING);
  };

  const rankActivity = async (rank: number) => {
    try {
      await setLoading();
      await activityRepository!.rankActivity(activityId, rank);
      setRequestStatus(ApiRequestStatus.SUCCESS);
      closeRatingModal();
      router.back();
    } catch (error) {
      setRequestStatus(ApiRequestStatus.ERROR);
    }
  };

  const closeRatingModal = () => {
    setRatingModal(false);
  };

  const openRatingModal = () => {
    setRatingModal(true);
  };

  return {
    rankActivity,
    requestStatus,
    ratingModal,
    closeRatingModal,
    openRatingModal,
  };
};
