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


type UpdateProfilePictureResponse = {
  uuid: string;
  firstName: string;
  lastName: string;
  email: string;
  mobileNumber: string;
  dialCode: string;
  profilePicture: string;
  emailVerified: boolean;
  roles: string[];
};

export default function useUpdateProfilePicture() {
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["user-profile-picture"],
    mutationFn: async ({
      userId,
      formData,
    }: {
      userId: string;
      formData: FormData;
    }) => {
      const res = await apiPatchForm<UpdateProfilePictureResponse>(
        PROFILE_ENDPOINTS.UPDATE_USER_PROFILE_PICTURE(userId),
        formData,
      );

      return res.data;
    },
    onSuccess: (data) => {
      successToast(SUCCESS_MESSAGES.UPDATE_PICTURE);
      dispatch(updateUser(data));
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onError: (error) => {
      errorToast("Failed to update profile picture");
    },
  });

  return { handleUpdateProfilePicture: mutateAsync, isPending };
}
