import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SearchMethodUdpGrid } from '../../../UI/templates/newGrid';
import { FluentDialog, LinearProgress } from '../../../UI';
import { useTransactionEngine } from '../../../utilities/transactions/useTransactionEngine';
import { useAxiosMutate } from '../../../utilities';
import { ConfigService } from '../../../configService';
import { useHandleAxiosSnackbar } from '../../../utilities';
import { TransactionUiActionTypeEnums, UdpSearchEnums } from '../../../enums';
const UDP_TRANSACTION_GRID_ID = '32c0fd0b-bb94-497a-b47a-6c7e8f746134';
const UdpTransactionGrid = (props) => {
    const { transactionTypeId, domainName, transactionTypeLoading, handleGridApiCallback, openAddTransaction, openViewTransaction, openEditTransaction, openAttachmentTransaction, openWorkflowActionTransaction, openCreateRevision, searchMethodObject, domainColumnFormatters = {}, refreshGridData, gridApi, initialFilterModel, initialGridOptions = {}, catalogObject, gridTitle, hideCreateTransaction = false, columnDefProperties, paginationAutoPageSize, customActions = [], calendarViewEnabled = false, onShowCalendarView } = props;
    const [dialogOpen, setDialogOpen] = useState(false);
    const [selectedTransaction, setSelectedTransaction] = useState(null);
    const { t } = useTranslation();
    const { hasRevisions, transactionTypeGridColumns, transactionTypeColumnDefProperties, transactionTypePageConfiguration, getUiActionRenderParameters, transactionTypeStatusColorsMap, getTransactionTypeLabel, transactionTypeStatuses, canCancel } = useTransactionEngine(transactionTypeId);
    const columnDefinitionProperties = useMemo(() => (Object.assign(Object.assign({}, transactionTypeColumnDefProperties), columnDefProperties)), [transactionTypeColumnDefProperties, columnDefProperties]);
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const [{ data, loading: cancelLoading, error: cancelError }, cancelTransaction] = useAxiosMutate(`${ConfigService.productV1ApiUrl}`, `udptransaction/${selectedTransaction === null || selectedTransaction === void 0 ? void 0 : selectedTransaction.transactionId}/cancelTransaction`, {
        method: 'post'
    }, {});
    const handleDialogClose = () => {
        setSelectedTransaction(null);
        setDialogOpen(false);
    };
    const handleConfirmActionDialog = useCallback(async () => {
        try {
            const response = await cancelTransaction();
            if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
                refreshGridData();
                handleSuccessSnackbar(t(`Transaction has been cancelled successfully`));
            }
            else {
                handleErrorSnackbar(new Error(t(`Error cancelling Transaction. Please try again later.`)));
            }
        }
        catch (error) {
            handleErrorSnackbar(error);
        }
        finally {
            handleDialogClose();
        }
    }, [
        cancelTransaction,
        refreshGridData,
        handleErrorSnackbar,
        handleSuccessSnackbar,
        t
    ]);
    const removeTimeFromDate = (date) => {
        const parsedDate = new Date(date);
        if (parsedDate.getTime()) {
            const year = parsedDate.getFullYear();
            //Month is zero based 0 = Jan so need to add 1
            const month = parsedDate.getMonth() + 1;
            const day = parsedDate.getDate().toString();
            return `${year}-${month.toString()}-${day}`;
        }
        return parsedDate;
    };
    const transactionLabel = useMemo(() => {
        var _a;
        return ((_a = getTransactionTypeLabel(selectedTransaction)) !== null && _a !== void 0 ? _a : selectedTransaction === null || selectedTransaction === void 0 ? void 0 : selectedTransaction.entityBusinessKey);
    }, [getTransactionTypeLabel, selectedTransaction]);
    const pdfViewPageId = useMemo(() => {
        var _a;
        return (_a = getUiActionRenderParameters(TransactionUiActionTypeEnums.Render_View_Pdf_Page)) === null || _a === void 0 ? void 0 : _a.pageId;
    }, [getUiActionRenderParameters]);
    const columnDefs = useMemo(() => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
        const initialColumnDefs = [
            {
                headerName: ((_a = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['transactionId']) === null || _a === void 0 ? void 0 : _a.displayName) ||
                    t('Transaction Id'),
                field: 'transactionId',
                hide: true,
                order: ((_b = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['transactionId']) === null || _b === void 0 ? void 0 : _b.order) ||
                    Number.MAX_SAFE_INTEGER
            },
            {
                headerName: ((_c = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['createdOn']) === null || _c === void 0 ? void 0 : _c.displayName) ||
                    t('Created On'),
                field: 'createdOn',
                hide: (_d = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['createdOn']) === null || _d === void 0 ? void 0 : _d.hide,
                order: ((_e = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['createdOn']) === null || _e === void 0 ? void 0 : _e.order) ||
                    Number.MAX_SAFE_INTEGER,
                cellDataType: 'dateString',
                valueFormatter: (params) => {
                    return removeTimeFromDate(params === null || params === void 0 ? void 0 : params.data.createdOn);
                }
            },
            {
                headerName: ((_f = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['currentStatusId']) === null || _f === void 0 ? void 0 : _f.displayName) ||
                    t('Current Status'),
                field: 'currentStatusId',
                hide: (_g = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['currentStatusId']) === null || _g === void 0 ? void 0 : _g.hide,
                order: ((_h = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['currentStatusId']) === null || _h === void 0 ? void 0 : _h.order) ||
                    Number.MAX_SAFE_INTEGER,
                cellRenderer: 'statusRenderer',
                cellRendererParams: {
                    statusMappingConfig: transactionTypeStatusColorsMap,
                    getStatusValue: (params) => params === null || params === void 0 ? void 0 : params.data.udpTransactionUdpTransactionTypeStatus.name
                },
                filter: 'agSetColumnFilter',
                filterParams: {
                    values: (params) => {
                        if (transactionTypeStatuses) {
                            params.success(transactionTypeStatuses);
                        }
                    },
                    keyCreator: (params) => params.value.transactionTypeStatusId,
                    valueFormatter: (params) => params.value.name
                },
                valueFormatter: (params) => params === null || params === void 0 ? void 0 : params.data.udpTransactionUdpTransactionTypeStatus.name
            },
            ...(hasRevisions
                ? [
                    {
                        headerName: ((_j = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['currentRevisionNo']) === null || _j === void 0 ? void 0 : _j.displayName) || t('Revision No'),
                        field: 'currentRevisionNo',
                        hide: (_k = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['currentRevisionNo']) === null || _k === void 0 ? void 0 : _k.hide,
                        order: ((_l = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['currentRevisionNo']) === null || _l === void 0 ? void 0 : _l.order) ||
                            Number.MAX_SAFE_INTEGER
                    }
                ]
                : []),
            {
                headerName: ((_m = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['lastEventTypeId']) === null || _m === void 0 ? void 0 : _m.displayName) ||
                    t('Last Event Type'),
                field: 'lastEventTypeId',
                hide: (_o = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['lastEventTypeId']) === null || _o === void 0 ? void 0 : _o.hide,
                order: ((_p = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['lastEventTypeId']) === null || _p === void 0 ? void 0 : _p.order) ||
                    Number.MAX_SAFE_INTEGER,
                valueFormatter: (params) => params === null || params === void 0 ? void 0 : params.data.udpTransactionUdpTransactionEventType.name
            },
            {
                headerName: ((_q = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['attachments']) === null || _q === void 0 ? void 0 : _q.displayName) ||
                    t('Attachments'),
                field: 'attachments',
                hide: (_r = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['attachments']) === null || _r === void 0 ? void 0 : _r.hide,
                pinned: 'right',
                maxWidth: 100,
                onCellClicked: (event) => {
                    openAttachmentTransaction(event.data);
                },
                valueFormatter: (params) => {
                    return params === null || params === void 0 ? void 0 : params.data.udpTransactionUdpTransactionAttachment.length;
                }
            },
            {
                headerName: ((_s = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['actions']) === null || _s === void 0 ? void 0 : _s.displayName) || t('Actions'),
                field: 'actions',
                hide: (_t = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties['actions']) === null || _t === void 0 ? void 0 : _t.hide,
                cellRenderer: 'actionsRenderer',
                cellRendererParams: {
                    actionList: [
                        {
                            id: 0,
                            title: t('Next Steps'),
                            iconName: 'panel-right-expand',
                            handleOnClick: (e, params) => {
                                openWorkflowActionTransaction(params === null || params === void 0 ? void 0 : params.data);
                            }
                        },
                        ...(pdfViewPageId
                            ? [
                                {
                                    id: 1,
                                    title: t('View'),
                                    iconName: 'view',
                                    handleOnClick: (e, params) => {
                                        openViewTransaction(params === null || params === void 0 ? void 0 : params.data);
                                    },
                                    disabled: !pdfViewPageId
                                }
                            ]
                            : []),
                        {
                            id: 2,
                            title: t('Edit'),
                            iconName: 'edit',
                            handleOnClick: (e, params) => {
                                openEditTransaction(params === null || params === void 0 ? void 0 : params.data);
                            }
                        },
                        ...(hasRevisions
                            ? [
                                {
                                    id: 3,
                                    title: t('Create Revision'),
                                    iconName: 'add',
                                    handleOnClick: (e, params) => {
                                        openCreateRevision(params === null || params === void 0 ? void 0 : params.data);
                                    },
                                    disabled: !hasRevisions
                                }
                            ]
                            : []),
                        ...(canCancel
                            ? [
                                {
                                    id: 4,
                                    title: t('Cancel'),
                                    iconName: 'close16',
                                    handleOnClick: (e, params) => {
                                        setSelectedTransaction(params === null || params === void 0 ? void 0 : params.data);
                                        setDialogOpen(true);
                                    }
                                }
                            ]
                            : []),
                        ...customActions
                    ]
                }
            }
        ];
        transactionTypeGridColumns === null || transactionTypeGridColumns === void 0 ? void 0 : transactionTypeGridColumns.forEach((gridColumn) => {
            var _a, _b, _c, _d, _e;
            const propertyName = (gridColumn === null || gridColumn === void 0 ? void 0 : gridColumn.propertyName) || '';
            let valueFormatter = (params) => {
                var _a;
                return (params === null || params === void 0 ? void 0 : params.data)
                    ? (_a = params === null || params === void 0 ? void 0 : params.data) === null || _a === void 0 ? void 0 : _a.entityBusinessObject[propertyName]
                    : '';
            };
            let onCellClicked = null;
            if (domainColumnFormatters[propertyName]) {
                valueFormatter = domainColumnFormatters[propertyName].formatter;
                onCellClicked =
                    domainColumnFormatters[propertyName].onCellClicked || null;
            }
            let agColumnFilter = 'agTextColumnFilter';
            let cellDataType = null;
            const matchingFieldInfo = (_a = catalogObject === null || catalogObject === void 0 ? void 0 : catalogObject.properties) === null || _a === void 0 ? void 0 : _a.find((objectProperty) => {
                return objectProperty.name === propertyName;
            });
            if ((matchingFieldInfo === null || matchingFieldInfo === void 0 ? void 0 : matchingFieldInfo.type.toLowerCase()) == 'datetime') {
                agColumnFilter = 'agDateColumnFilter';
                cellDataType = 'dateString';
            }
            const propertyPrefix = !!matchingFieldInfo
                ? `${UdpSearchEnums.UdpBusinessDomainPrefix}.`
                : '';
            const propertyVarPrefix = !!matchingFieldInfo
                ? `${UdpSearchEnums.UdpBusinessDomainPrefix}_`
                : '';
            initialColumnDefs.push({
                headerName: gridColumn === null || gridColumn === void 0 ? void 0 : gridColumn.displayName,
                field: `${propertyPrefix}${domainName}.${propertyName}`,
                hide: (_b = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${propertyVarPrefix}${propertyName}`]) === null || _b === void 0 ? void 0 : _b.hide,
                order: ((_c = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${propertyVarPrefix}${propertyName}`]) === null || _c === void 0 ? void 0 : _c.order) || Number.MAX_SAFE_INTEGER,
                valueFormatter: valueFormatter,
                onCellClicked: onCellClicked,
                cellRenderer: ((_d = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${propertyVarPrefix}${propertyName}`]) === null || _d === void 0 ? void 0 : _d.cellRenderer) || null,
                cellRendererParams: ((_e = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${propertyVarPrefix}${propertyName}`]) === null || _e === void 0 ? void 0 : _e.cellRendererParams) || null,
                filter: agColumnFilter,
                cellDataType: cellDataType
            });
        });
        Object.keys(domainColumnFormatters).forEach((columnKey) => {
            var _a, _b, _c, _d;
            const gridColumnPropertyNames = transactionTypeGridColumns === null || transactionTypeGridColumns === void 0 ? void 0 : transactionTypeGridColumns.map((col) => col.propertyName);
            if (!(gridColumnPropertyNames === null || gridColumnPropertyNames === void 0 ? void 0 : gridColumnPropertyNames.includes(columnKey))) {
                let formatedHeaderName = columnKey.slice(0, 1).toUpperCase() + columnKey.slice(1);
                initialColumnDefs.push({
                    headerName: formatedHeaderName,
                    field: `${UdpSearchEnums.UdpBusinessDomainPrefix}.${domainName}.${columnKey}`,
                    hide: (_a = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]) === null || _a === void 0 ? void 0 : _a.hide,
                    order: ((_b = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]) === null || _b === void 0 ? void 0 : _b.order) || Number.MAX_SAFE_INTEGER,
                    valueFormatter: domainColumnFormatters[columnKey].formatter,
                    onCellClicked: domainColumnFormatters[columnKey].onCellClicked || null,
                    cellRenderer: ((_c = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]) === null || _c === void 0 ? void 0 : _c.cellRenderer) || null,
                    cellRendererParams: ((_d = columnDefinitionProperties === null || columnDefinitionProperties === void 0 ? void 0 : columnDefinitionProperties[`${UdpSearchEnums.UdpBusinessDomainPrefix}_${columnKey}`]) === null || _d === void 0 ? void 0 : _d.cellRendererParams) || null
                });
            }
        });
        if (columnDefinitionProperties) {
            const ordered = initialColumnDefs.sort((a, b) => a.order - b.order);
            return ordered;
        }
        return initialColumnDefs;
    }, [
        domainName,
        t,
        openViewTransaction,
        openEditTransaction,
        openAttachmentTransaction,
        openWorkflowActionTransaction,
        domainColumnFormatters,
        transactionTypeGridColumns,
        openCreateRevision,
        hasRevisions,
        pdfViewPageId,
        transactionTypeStatusColorsMap,
        catalogObject,
        transactionTypeStatuses,
        canCancel,
        columnDefinitionProperties,
        customActions
    ]);
    const headerConfig = {
        title: gridTitle || (transactionTypePageConfiguration === null || transactionTypePageConfiguration === void 0 ? void 0 : transactionTypePageConfiguration.gridTitle) || domainName,
        primaryActionButton: hideCreateTransaction ||
            (transactionTypePageConfiguration === null || transactionTypePageConfiguration === void 0 ? void 0 : transactionTypePageConfiguration.hideCreateTransaction)
            ? null
            : {
                label: (transactionTypePageConfiguration === null || transactionTypePageConfiguration === void 0 ? void 0 : transactionTypePageConfiguration.createTransactionButtonLabel) ||
                    `${domainName} Entry`,
                iconName: 'add',
                onClick: () => {
                    openAddTransaction();
                }
            },
        secondaryActionButtons: calendarViewEnabled
            ? [
                {
                    iconOnly: true,
                    iconName: 'calendar',
                    label: t('Calendar View'),
                    onClick: () => onShowCalendarView === null || onShowCalendarView === void 0 ? void 0 : onShowCalendarView()
                }
            ]
            : undefined
    };
    const gridFunctions = [
        { name: 'openSavedViews' },
        { name: 'agGridExport' },
        { name: 'agGridHideShowColumns' },
        { name: 'agGridSizeColumnsToFit' },
        { name: 'agGridAutoSizeColumns' },
        { name: 'agGridResetColumns' }
    ];
    const gridOptions = useMemo(() => {
        var _a;
        return Object.assign({ pagination: true, paginationAutoPageSize: (_a = paginationAutoPageSize !== null && paginationAutoPageSize !== void 0 ? paginationAutoPageSize : transactionTypePageConfiguration === null || transactionTypePageConfiguration === void 0 ? void 0 : transactionTypePageConfiguration.paginationAutoPageSize) !== null && _a !== void 0 ? _a : true, rowSelection: 'none' }, initialGridOptions);
    }, [
        initialGridOptions,
        paginationAutoPageSize,
        transactionTypePageConfiguration
    ]);
    const searchMethodConfig = useMemo(() => {
        let combinedSearchObject = {
            eagerLoad: true,
            filterElements: [
                {
                    searchField: 'transactionTypeId',
                    searchOperator: '=',
                    searchValue: transactionTypeId
                },
                {
                    searchField: 'isDeleted',
                    searchOperator: '=',
                    searchValue: false
                }
            ]
        };
        if (searchMethodObject) {
            let combinedFilterElems = combinedSearchObject.filterElements.concat((searchMethodObject === null || searchMethodObject === void 0 ? void 0 : searchMethodObject.filterElements) || []);
            combinedSearchObject = Object.assign(Object.assign({}, combinedSearchObject), searchMethodObject);
            combinedSearchObject = Object.assign(Object.assign({}, combinedSearchObject), { filterElements: combinedFilterElems });
        }
        return {
            requestUrl: `${ConfigService.productV1ApiUrl}/UdpTransaction/search`,
            customSearchObject: combinedSearchObject
        };
    }, [transactionTypeId, searchMethodObject]);
    useEffect(() => {
        if (gridApi &&
            initialFilterModel &&
            Object.keys(initialFilterModel).length) {
            // 1. Set the filter model
            gridApi.setFilterModel(initialFilterModel);
            // 2. Inform the grid that filters have changed, which re-runs the data fetch (Server-Side)
            gridApi.onFilterChanged();
        }
    }, [gridApi, initialFilterModel]);
    return (React.createElement(React.Fragment, null, transactionTypeLoading && React.createElement(LinearProgress, null), React.createElement(SearchMethodUdpGrid, { gridHeaderConfig: headerConfig, gridFunctions: gridFunctions, gridOptions: gridOptions, columnDefs: columnDefs, searchMethodConfig: searchMethodConfig, gridApiCallback: handleGridApiCallback, gridId: UDP_TRANSACTION_GRID_ID, entityName: domainName }), React.createElement(FluentDialog, { title: t(`Cancel Transaction`), message: `Are you sure you want to cancel the transaction for ${transactionLabel || domainName}
        ?`, labelOne: t('Confirm'), actionOne: handleConfirmActionDialog, labelTwo: t('Cancel'), actionTwo: handleDialogClose, open: dialogOpen, handleClose: handleDialogClose, loading: cancelLoading })));
};
export default UdpTransactionGrid;
//# sourceMappingURL=UdpTransactionGrid.js.map