import React, { useCallback, useMemo, useState } from 'react';
import { PageContainer } from '../../../../page/PageContainer';
import { useTransactionEngine } from '../../../../utilities/transactions/useTransactionEngine';
import { TransactionUiActionTypeEnums } from '../../../../enums';
import { Form, FormSpy } from '../../../../utilities/form';
import { ConfigService } from 'udp-react-stencil-component-library';
import { apiMutate } from '../../../../utilities';
import { useHandleAxiosSnackbar } from '../../../../utilities/apiHelpers';
import { useTranslation } from 'react-i18next';
const UdpTransactionCustomPage = (props) => {
    const { pageId, transactionTypeId, transactionUiActionType, formRef, refetchTransaction, transaction, transactionTypeTransactionActionId, setHasUnsavedChanges, onSubmitSuccess, refreshGridData, additionalPageParms = {} } = props;
    const [pageOnSubmitSuccess, setPageOnSubmitSuccess] = useState(null);
    const { getUiActionRenderParameters, getHiddenFields, getRequiredFields } = useTransactionEngine(transactionTypeId);
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const { t } = useTranslation();
    const executeCreateTransactionAction = useCallback(async (data) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/transactionType/${transactionTypeId}/create`, {
        method: 'post'
    }, data), [transactionTypeId]);
    const executeSaveChanges = useCallback(async (data) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${transaction === null || transaction === void 0 ? void 0 : transaction.transactionId}/saveChanges`, {
        method: 'put'
    }, data), [transaction === null || transaction === void 0 ? void 0 : transaction.transactionId]);
    const executeCreateRevision = useCallback(async (data) => apiMutate(ConfigService.productV1ApiUrl, `udpTransaction/${transaction === null || transaction === void 0 ? void 0 : transaction.transactionId}/createRevision`, {
        method: 'post'
    }, data), [transaction === null || transaction === void 0 ? void 0 : transaction.transactionId]);
    const executeSubmitCustomAction = useCallback(async (data) => apiMutate(ConfigService.productV1ApiUrl, `udptransactiontypeTransactionAction/${transactionTypeTransactionActionId}/transaction/${transaction.transactionId}/submit`, {
        method: 'post'
    }, data), [transactionTypeTransactionActionId, transaction === null || transaction === void 0 ? void 0 : transaction.transactionId]);
    const executeSubmitActionApi = useCallback(async (data, actionApiId) => apiMutate(ConfigService.productV1ApiUrl, `udpTransactionWorkflowActionApi/${actionApiId}/transaction/${transaction.transactionId}/submit`, {
        method: 'post'
    }, data), [transaction === null || transaction === void 0 ? void 0 : transaction.transactionId]);
    const onSubmit = useCallback(async (values) => {
        var _a, _b, _c;
        try {
            const request = { data: values };
            const actionApiId = transactionUiActionType
                ? (_a = getUiActionRenderParameters(transactionUiActionType)) === null || _a === void 0 ? void 0 : _a.actionApiId
                : null;
            let response = null;
            let message = '';
            let errorMessagePart = '';
            if (transactionUiActionType ===
                TransactionUiActionTypeEnums.Render_Create_Transaction_Page) {
                if (actionApiId) {
                    response = await executeSubmitActionApi(request, actionApiId);
                }
                else {
                    response = await executeCreateTransactionAction(request);
                }
                message = 'Transaction has been created successfully';
                errorMessagePart = 'creating';
            }
            else if (transactionUiActionType ===
                TransactionUiActionTypeEnums.Render_Transaction_Details_Page) {
                if (actionApiId) {
                    response = await executeSubmitActionApi(request, actionApiId);
                }
                else {
                    response = await executeSaveChanges(request);
                }
                message = 'Transaction has been saved successfully';
                errorMessagePart = 'saving';
            }
            else if (transactionUiActionType ===
                TransactionUiActionTypeEnums.Render_Create_Revision_Page) {
                if (actionApiId) {
                    response = await executeSubmitActionApi(request, actionApiId);
                }
                else {
                    response = await executeCreateRevision(request);
                }
                message = 'Revision has been created successfully';
                errorMessagePart = 'creating revision for';
            }
            else if (!!transactionTypeTransactionActionId) {
                response = await executeSubmitCustomAction(request);
                message = 'Action has been submitted successfully';
                errorMessagePart = 'submitting action for';
            }
            const { status, data } = response || {};
            const apiResult = data === null || data === void 0 ? void 0 : data.actionApiResult;
            if (status === 200) {
                // Success condition: No actionApiResult OR actionApiResult says success is true
                const isSuccessful = !apiResult || apiResult.success;
                if (isSuccessful) {
                    handleSuccessSnackbar(t(`${message}`));
                    onSubmitSuccess === null || onSubmitSuccess === void 0 ? void 0 : onSubmitSuccess(response);
                    pageOnSubmitSuccess === null || pageOnSubmitSuccess === void 0 ? void 0 : pageOnSubmitSuccess(data);
                }
                else if (apiResult === null || apiResult === void 0 ? void 0 : apiResult.errorMessage) {
                    handleErrorSnackbar(new Error(apiResult.errorMessage));
                }
            }
            else {
                // Handle non-200 status codes
                const defaultError = t(`Error ${errorMessagePart} Transaction. Please try again later.`);
                handleErrorSnackbar(new Error(defaultError));
            }
        }
        catch (error) {
            handleErrorSnackbar(error);
        }
        finally {
            if (setHasUnsavedChanges) {
                (_c = (_b = formRef.current) === null || _b === void 0 ? void 0 : _b.form) === null || _c === void 0 ? void 0 : _c.restart(values);
                setHasUnsavedChanges(false);
            }
            if (refetchTransaction) {
                refetchTransaction();
            }
        }
    }, [
        executeCreateTransactionAction,
        executeSaveChanges,
        executeCreateRevision,
        handleErrorSnackbar,
        handleSuccessSnackbar,
        transactionUiActionType,
        executeSubmitCustomAction,
        t,
        transactionTypeTransactionActionId,
        setHasUnsavedChanges,
        formRef,
        onSubmitSuccess,
        refetchTransaction,
        pageOnSubmitSuccess,
        executeSubmitActionApi,
        getUiActionRenderParameters
    ]);
    const isFieldRequired = useCallback((fieldName) => {
        const requiredFields = getRequiredFields(transaction);
        return requiredFields === null || requiredFields === void 0 ? void 0 : requiredFields.includes(fieldName);
    }, [getRequiredFields, transaction]);
    const isFieldHidden = useCallback((fieldName) => {
        const hiddenFields = getHiddenFields(transaction);
        return hiddenFields === null || hiddenFields === void 0 ? void 0 : hiddenFields.includes(fieldName);
    }, [getHiddenFields, transaction]);
    const transactionPageId = useMemo(() => {
        var _a;
        if (pageId) {
            return pageId;
        }
        return (_a = getUiActionRenderParameters(transactionUiActionType)) === null || _a === void 0 ? void 0 : _a.pageId;
    }, [getUiActionRenderParameters, transactionUiActionType, pageId]);
    if (!transactionPageId) {
        return null;
    }
    return (React.createElement(Form, { onSubmit: onSubmit, ref: formRef }, React.createElement(FormSpy, { subscription: { dirty: true } }, ({ dirty }) => {
        if (setHasUnsavedChanges) {
            setHasUnsavedChanges(dirty);
        }
    }), React.createElement(PageContainer, { pageId: transactionPageId, updateLocationState: false, widgetParams: Object.assign({ transaction,
            isFieldRequired,
            isFieldHidden, refreshTransactionGrid: refreshGridData, setOnSubmitSuccess: setPageOnSubmitSuccess }, additionalPageParms) })));
};
export default UdpTransactionCustomPage;
//# sourceMappingURL=UdpTransactionCustomPage.js.map