import { useChangePasswordMutation, useGetAuthenticatedUserDataQuery, useUpdateUserMutation } from "../../../Api/usersApi.js"; import {useDispatch} from "react-redux"; import {openEditProfileModal, closeEditProfileModal} from "../../../Redux/Slices/usersSlice.js"; import {notification} from "antd"; const useProfilePage = () => { const dispatch = useDispatch(); const { data: userData = {}, isLoading: isLoadingUserData, isError: isErrorUserData, } = useGetAuthenticatedUserDataQuery(undefined, { pollingInterval: 20000, }); const [updateUserProfile, {isLoading: isUpdatingProfile}] = useUpdateUserMutation(); const [changePassword, {isLoading: isChangingPassword}] = useChangePasswordMutation(); const handleEditProfile = () => { dispatch(openEditProfileModal()); }; const handleCancelEdit = () => { dispatch(closeEditProfileModal()); }; const handleSubmitProfile = async (values) => { try { const profileData = { first_name: values.first_name, last_name: values.last_name, patronymic: values.patronymic || null, login: userData.login, }; await updateUserProfile({userId: userData.id, ...profileData}).unwrap(); notification.success({ message: "Успех", description: "Профиль успешно обновлен.", placement: "topRight", }); dispatch(closeEditProfileModal()); } catch (error) { notification.error({ message: "Ошибка", description: error?.data?.detail || "Не удалось обновить профиль.", placement: "topRight", }); } }; const handleSubmitPassword = async (values) => { try { const passwordData = { current_password: values.current_password, new_password: values.new_password, confirm_password: values.confirm_password, user_id: userData.id, }; await changePassword(passwordData).unwrap(); notification.success({ message: "Успех", description: "Пароль успешно изменен.", placement: "topRight", }); dispatch(closeEditProfileModal()); } catch (error) { notification.error({ message: "Ошибка", description: error?.data?.detail || "Не удалось изменить пароль.", placement: "topRight", }); } }; return { userData, isLoading: isLoadingUserData, isError: isErrorUserData, isUpdating: isUpdatingProfile || isChangingPassword, handleEditProfile, handleCancelEdit, handleSubmitProfile, handleSubmitPassword, }; }; export default useProfilePage;