import { notifications } from "@mantine/notifications"; import { useQueryClient } from "@tanstack/react-query"; import { useEffect, useRef, useState } from "react"; import { useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { ApiErrorCode, apiErrorCode, apiQueryClient, isApiErrorCode, } from "@/shared/api"; import { commitTbankConnectionBoundary, type TbankConnectionStatus, } from "../../model/connection-boundary"; function useTbankConnectionSectionLoadedVm(status: TbankConnectionStatus) { const { t } = useTranslation(); const queryClient = useQueryClient(); const [isDeleteOpened, setIsDeleteOpened] = useState(false); const removalButtonRef = useRef(null); const { formState: { errors }, handleSubmit, register, reset, } = useForm<{ token: string }>(); const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", { onSuccess: (data) => { commitTbankConnectionBoundary(queryClient, data); reset(); if (status.connected && data.connected) notifications.show({ id: "tbank-token-replaced-" + crypto.randomUUID(), message: t("tbank.tokenReplaced"), }); }, }); const remove = apiQueryClient.useMutation( "delete", "/api/v1/tbank-connection", { onSuccess: () => { commitTbankConnectionBoundary(queryClient, { connected: false, connectedAt: null, }); setIsDeleteOpened(false); }, }, ); const requestError = apiErrorCode(update.error); const unavailableMessage = isApiErrorCode( requestError, ApiErrorCode.TbankUnavailable, ) ? "tbank.unavailable" : "tbank.requestError"; const isPending = update.isPending || remove.isPending; const isConnected = status.connected; useEffect(() => { if (isDeleteOpened && remove.isError) removalButtonRef.current?.focus(); }, [isDeleteOpened, remove.isError]); const onSubmit = handleSubmit(({ token }) => { update.mutate({ body: { token } }); }); const onOpenDisconnect = () => { remove.reset(); setIsDeleteOpened(true); }; const onCloseDisconnect = () => !isPending && setIsDeleteOpened(false); const onConfirmDisconnect = () => remove.mutate({}); return { errors, isConnected, isDeleteOpened, isPending, onCloseDisconnect, onConfirmDisconnect, onOpenDisconnect, onSubmit, register, removalButtonRef, remove, requestError, status, t, unavailableMessage, update, }; } export { useTbankConnectionSectionLoadedVm };