import { useEffect, useState } from "react";
import { useChangeInterests } from "./useChangeInterests";
import { useGetUserInterests } from "./useGetUserInterests";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { useGetInterests } from "./useGetInterests";
import { router } from "expo-router";

export const useUpdateInterests = () => {
  const { data: userCategories, requestStatus: userInterestsRequest } =
    useGetUserInterests();
  const { interests: allCategories, requestStatus: changeInterestsRequest } =
    useGetInterests();
  const {
    interests,
    toogleInterest,
    onSubmit: onSubmitInterests,
    setAllInterests,
  } = useChangeInterests();
  const [requestStatus, setRequestStatus] = useState<ApiRequestStatus>(
    ApiRequestStatus.LOADING
  );

  useEffect(() => {
    const requests = [changeInterestsRequest, userInterestsRequest];
    if (requests.every((request) => request === ApiRequestStatus.SUCCESS)) {
      setAllInterests(
        allCategories!.map((category) => ({
          ...category,
          isSelected: userCategories!.some(
            (userCategory) => userCategory.id === category.id
          ),
        }))
      );
      setRequestStatus(ApiRequestStatus.SUCCESS);
    }
  }, [changeInterestsRequest, userInterestsRequest]);

  const onSubmit = async () => {
    /*     await handleSubmit((data) => {
          
        })(); */

    try {
      await onSubmitInterests();
      router.back();
    } catch (error) {
      console.log(error);
    }
  };
  return { onSubmit, toogleInterest, interests, requestStatus };
};
