import React, { useState, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { DocumentIcon } from '@fluentui/react-icons';
import { FluentDialog, SideSheet } from '../../../../UI';
import { useAxiosMutate } from '../../../../utilities';
import { ConfigService } from '../../../../configService';
import { UdpActionCard } from '../../../../UI/inputs/buttons/UdpActionCard/UdpActionCard';
import { getIconFromName } from '../../../../utilities/tree';
import './WorkflowActions.css';
import { TransactionActionTypeEnums, TransactionEventTypeEnums } from '../../../../enums/unitySystemEnums';
import { useTransactionEngine } from '../../../../utilities/transactions/useTransactionEngine';
import UdpTransactionCustomPage from '../components/UdpTransactionCustomPage';
import { useHandleAxiosSnackbar } from '../../../../utilities/apiHelpers';
const TransactionActionButton = ({ icon, primaryText, secondaryText, onClick, action }) => {
    const actionCardIcon = useMemo(() => getIconFromName(icon), [icon]);
    return (React.createElement(UdpActionCard, { icon: actionCardIcon ? actionCardIcon : DocumentIcon, primaryText: primaryText, secondaryText: secondaryText, onClick: () => {
            onClick(action);
        } }));
};
const WorkflowActions = ({ transaction, closeSideSheet, refreshGridData, handleSidesheet }) => {
    var _a;
    const [dialogOpen, setDialogOpen] = useState(true);
    const [dialogUserStrings, setDialogUserStrings] = useState(null);
    const [selectedAction, setSelectedAction] = useState(null);
    const [sideSheetOpen, setSideSheetOpen] = useState(false);
    const [loading, setLoading] = useState(false);
    const [sidesheetPrimaryButtonDisabled, setSidesheetPrimaryButtonDisabled] = useState(false);
    const formRef = useRef(null);
    const { getTransactionTypeTransactionActions } = useTransactionEngine(transaction === null || transaction === void 0 ? void 0 : transaction.transactionTypeId);
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const handleOnCloseSideSheet = useCallback(() => {
        setSideSheetOpen(false);
    }, []);
    const handleSubmitWorkflowAction = useCallback(async () => {
        var _a, _b;
        setLoading(true);
        await ((_b = (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.submit());
        setLoading(false);
    }, [formRef]);
    const handleSubmitSuccessfulWorkflowAction = useCallback((response) => {
        handleOnCloseSideSheet();
        closeSideSheet();
        refreshGridData();
    }, [handleOnCloseSideSheet, refreshGridData, closeSideSheet]);
    const transactionTypeTransactionActions = useMemo(() => {
        return (getTransactionTypeTransactionActions(transaction, TransactionEventTypeEnums.Sidesheet) || []);
    }, [getTransactionTypeTransactionActions, transaction]);
    // Base URL and url get overwritten in postTransactionData function call in handleConfirmActionDialog()
    const [{ data: transactionData }, postTransactionData] = useAxiosMutate(`${ConfigService.productV1ApiUrl}`, 'udptransactiontypeTransactionAction', {
        method: 'post'
    }, {});
    const i18n = useTranslation().t;
    const handleDialogOpen = useCallback((title, message) => {
        setDialogUserStrings({ title, message });
        setDialogOpen(true);
    }, []);
    const handleDialogClose = useCallback(() => {
        setDialogOpen(false);
    }, []);
    const handleConfirmActionDialog = useCallback(async () => {
        setDialogOpen(true);
        handleDialogClose();
        setLoading(true);
        try {
            const response = await postTransactionData({
                // Change URL to config
                url: `${ConfigService.productV1ApiUrl}` +
                    `/udptransactiontypeTransactionAction/${selectedAction.transactionTypeTransactionActionId}/transaction/${transaction.transactionId}/submit`,
                data: {}
            });
            const { status, data } = response || {};
            const apiResult = data === null || data === void 0 ? void 0 : data.actionApiResult;
            if (status === 200) {
                const isSuccessful = !apiResult || apiResult.success;
                if (isSuccessful) {
                    handleSuccessSnackbar(i18n('Successfully submitted!'));
                    closeSideSheet();
                    refreshGridData();
                }
                else if (apiResult === null || apiResult === void 0 ? void 0 : apiResult.errorMessage) {
                    handleErrorSnackbar(new Error(apiResult.errorMessage));
                }
            }
        }
        catch (event) {
            handleSuccessSnackbar(i18n(event.message));
        }
        setLoading(false);
    }, [
        postTransactionData,
        handleDialogClose,
        transaction,
        selectedAction,
        i18n,
        closeSideSheet,
        refreshGridData,
        handleSuccessSnackbar,
        handleErrorSnackbar
    ]);
    const handleOnActionClick = useCallback((action) => {
        const pageId = action.parameters.pageId;
        setSelectedAction(action);
        if (pageId) {
            setSideSheetOpen(true);
        }
        else if (action.transactionActionId == TransactionActionTypeEnums.Open_Edit_Transaction_Sidesheet) {
            handleSidesheet('edit', true, transaction);
        }
        else {
            handleDialogOpen(action.name, action.description);
        }
    }, [handleDialogOpen, transaction, handleSidesheet]);
    const TransactionActionButtons = useMemo(() => {
        if (!transactionTypeTransactionActions.length) {
            return null;
        }
        return transactionTypeTransactionActions === null || transactionTypeTransactionActions === void 0 ? void 0 : transactionTypeTransactionActions.map((action) => (React.createElement(TransactionActionButton, { key: action.transactionTypeTransactionActionId, primaryText: action.name, secondaryText: action.description, icon: action.icon, onClick: handleOnActionClick, action: action })));
    }, [transactionTypeTransactionActions, handleOnActionClick]);
    return (React.createElement(React.Fragment, null, React.createElement("div", { className: "transaction-action-buttons-container" }, TransactionActionButtons), dialogUserStrings && (React.createElement(FluentDialog, { title: i18n(`Are you sure you want to proceed with \"${dialogUserStrings.title}\"?`), message: dialogUserStrings.message, labelOne: i18n('Confirm'), actionOne: handleConfirmActionDialog, labelTwo: i18n('Cancel'), actionTwo: handleDialogClose, open: dialogOpen, handleClose: handleDialogClose })), React.createElement(SideSheet, { open: sideSheetOpen, title: selectedAction === null || selectedAction === void 0 ? void 0 : selectedAction.name, onClose: handleOnCloseSideSheet, width: 600, buttonLabel: i18n('Submit'), onSubmit: handleSubmitWorkflowAction, progress: loading, variant: "indeterminate", color: "primary", buttonOneDisabled: loading || sidesheetPrimaryButtonDisabled }, selectedAction && ((_a = selectedAction.parameters) === null || _a === void 0 ? void 0 : _a.pageId) && (React.createElement(UdpTransactionCustomPage, { pageId: selectedAction.parameters.pageId, transaction: transaction, formRef: formRef, transactionTypeTransactionActionId: selectedAction.transactionTypeTransactionActionId, onSubmitSuccess: handleSubmitSuccessfulWorkflowAction, refreshGridData: refreshGridData, additionalPageParms: {
            sidesheetParams: {
                setSidesheetPrimaryButtonDisabled
            }
        } })))));
};
export default WorkflowActions;
//# sourceMappingURL=WorkflowActions.js.map