import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiPatch } from "../../../../lib/api/methods";
import { PROFILE_ENDPOINTS } from "../endpoints";
import { EditProfileSchema } from "./schema";
import { errorToast, successToast } from "../../../../utils/toast";
import { ProfileResponse } from "../useProfileFetch";
import { useAppDispatch } from "../../../useAppRedux";
import { updateUser } from "../../../../store/slices/user";
import { SUCCESS_MESSAGES } from "./messages";


type EditProfileResponse = ProfileResponse;

export default function useEditProfile() {
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["edit-profile"],
    mutationFn: async (data: EditProfileSchema) => {
      const res = await apiPatch<EditProfileResponse>(
        PROFILE_ENDPOINTS.EDIT_PROFILE,
        {
          firstName: data.firstName,
          lastName: data.lastName,
          mobileNumber: data.mobileNumber.number,
          dialCode: data.mobileNumber.dialCode,
        },
      );
      return res;
    },
    onSuccess: (data) => {
      successToast(SUCCESS_MESSAGES.UPDATE_PROFILE);
      const user = data.data;
      dispatch(updateUser(user));
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onError: (error: any) => {
      errorToast(error?.response?.data?.message ?? "Something went wrong.");
    },
  });

  return { handleEditProfile: mutateAsync, loading: isPending };
}
