import UdpTransactionGrid from './UdpTransactionGrid';
import UdpTransactionCalendar from './UdpTransactionCalendar';
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import UdpTransactionSidesheet from './UdpTransactionSidesheet';
import { useTransactionType } from '../../../hooks/useTransactionType';
import { useTransactionEngine } from '../../../utilities/transactions/useTransactionEngine';
import { CircularProgress } from '@material-ui/core';
import './UdpTransactionsPage.css';
import { useUdpGridFilterModel } from '../../../hooks/useUdpGridFilterModel';
import { useCatalogStore } from '../../../stores';
import { useLocation } from 'react-router-dom';
import { Typography } from '../../../UI/dataDisplay/typography';
import { useAxiosGet } from '../../../utilities';
import { ConfigService } from '../../../configService';
// const domainColumnFormattersExample = {
//   submittedBy: {
//     formatter: (params) => {
//       return params?.data
//         ? params?.data?.entityBusinessObject['submittedBy']
//         : '';
//     }
//   },
//   submittedTo: {
//     formatter: (params) => {
//       return params?.data
//         ? params?.data?.entityBusinessObject['submittedTo']
//         : '';
//     }
//   },
//   test: {
//     formatter: (params) => {
//       return 'test';
//     }
//   }
// };
const UdpTransactionsPage = (props) => {
    var _a;
    const { transactionTypeId = '', domainName: initialDomainName = '', domainFieldType, domainFieldValue, searchMethodObject, domainColumnFormatters, gridOptions, onBeforeRefresh, onAfterRefresh, gridTitle, hideCreateTransaction = false, sideSheetProps, columnDefProperties, paginationAutoPageSize, customActions, gridApiCallback, loading = false } = props;
    const [sidesheetState, setSidesheetState] = useState({
        workflowAction: false,
        addTransaction: false,
        editTransaction: false,
        viewTransaction: false,
        attachmentTransaction: false,
        createRevision: false
    });
    const [selectedTransaction, setSelectedTransaction] = useState(null);
    const [gridApi, setGridApi] = useState(null);
    const [calendarRefresh, setCalendarRefresh] = useState(null);
    const [showCalendarView, setShowCalendarView] = useState(false);
    const location = useLocation();
    const state = location.state;
    let searchParamStr = location.search;
    let searchParams = new URLSearchParams(searchParamStr);
    const initialTransactionTypeId = ((_a = state === null || state === void 0 ? void 0 : state.params) === null || _a === void 0 ? void 0 : _a.udpTransactionTypeId)
        ? state.params.udpTransactionTypeId
        : searchParams.has('udpTransactionTypeId') === true
            ? searchParams.get('udpTransactionTypeId')
            : '';
    const { data: transactionType, loading: transactionTypeLoading, error: transactionTypeError } = useTransactionType({
        transactionTypeId: transactionTypeId || initialTransactionTypeId,
        domainName: initialDomainName,
        domainFieldType: domainFieldType,
        domainFieldValue: domainFieldValue
    });
    useTransactionEngine(transactionType === null || transactionType === void 0 ? void 0 : transactionType.transactionTypeId);
    const currentApiCatalogId = useCatalogStore((state) => state.currentApiCatalogId);
    const filterModel = useUdpGridFilterModel();
    const handleSidesheet = (actionType, openStatus, transaction, width = 800) => {
        if (actionType == 'add') {
            setSidesheetState((prev) => (Object.assign(Object.assign({}, prev), { addTransaction: openStatus, width })));
        }
        else if (actionType == 'edit') {
            setSidesheetState((prev) => (Object.assign(Object.assign({}, prev), { editTransaction: openStatus, width })));
        }
        else if (actionType == 'view') {
            setSidesheetState((prev) => (Object.assign(Object.assign({}, prev), { viewTransaction: openStatus, width })));
        }
        else if (actionType == 'attachment') {
            setSidesheetState((prev) => (Object.assign(Object.assign({}, prev), { attachmentTransaction: openStatus, width })));
        }
        else if (actionType == 'action') {
            setSidesheetState((prev) => (Object.assign(Object.assign({}, prev), { workflowAction: openStatus, width })));
        }
        else if (actionType == 'createRevision') {
            setSidesheetState((prev) => (Object.assign(Object.assign({}, prev), { createRevision: openStatus, width })));
        }
        if (transaction) {
            setSelectedTransaction(transaction);
        }
    };
    const handleAttachmentTransaction = () => { };
    const handleGridApiCallback = useCallback((api) => {
        setGridApi(api);
        gridApiCallback === null || gridApiCallback === void 0 ? void 0 : gridApiCallback(api);
    }, [gridApiCallback]);
    const handleCalendarApiCallback = useCallback((refreshFn) => {
        setCalendarRefresh(() => refreshFn);
    }, []);
    const domainName = useMemo(() => {
        if (transactionType) {
            const splitDomainNameArr = transactionType.domainName.split('.');
            return splitDomainNameArr.pop();
        }
        return initialDomainName;
    }, [transactionType, initialDomainName]);
    const calendarViewConfiguration = useMemo(() => {
        var _a;
        const config = (_a = transactionType === null || transactionType === void 0 ? void 0 : transactionType.pageConfiguration) === null || _a === void 0 ? void 0 : _a.calendarViewConfiguration;
        if (!config)
            return null;
        return {
            enabled: config.enabled,
            isDefaultView: !!config.isDefaultView,
            domainStartDateProperty: config.domainStartDateProperty,
            domainEndDateProperty: config.domainEndDateProperty,
            domainPropertyToDisplay: config.domainPropertyToDisplay,
            defaultCalendarViewType: config.defaultCalendarViewType
        };
    }, [transactionType]);
    const calendarViewEnabled = !!(calendarViewConfiguration === null || calendarViewConfiguration === void 0 ? void 0 : calendarViewConfiguration.enabled);
    useEffect(() => {
        if (calendarViewConfiguration === null || calendarViewConfiguration === void 0 ? void 0 : calendarViewConfiguration.isDefaultView) {
            setShowCalendarView(true);
        }
    }, [calendarViewConfiguration === null || calendarViewConfiguration === void 0 ? void 0 : calendarViewConfiguration.isDefaultView]);
    const [{ data: catalogObject, loading: catalogObjectLoading }] = useAxiosGet(ConfigService.integrationV2ApiUrl, `apiCatalog/${currentApiCatalogId}/catalogObject/${transactionType === null || transactionType === void 0 ? void 0 : transactionType.domainName}`, {}, !!!currentApiCatalogId || !!!(transactionType === null || transactionType === void 0 ? void 0 : transactionType.domainName), false);
    const refreshGridData = useCallback(async () => {
        if (onBeforeRefresh) {
            await onBeforeRefresh(gridApi);
        }
        if (showCalendarView) {
            await (calendarRefresh === null || calendarRefresh === void 0 ? void 0 : calendarRefresh());
        }
        else {
            gridApi === null || gridApi === void 0 ? void 0 : gridApi.refreshServerSide();
        }
        if (onAfterRefresh) {
            await onAfterRefresh(gridApi);
        }
    }, [gridApi, calendarRefresh, showCalendarView, onBeforeRefresh, onAfterRefresh]);
    if (!transactionTypeId && !initialTransactionTypeId && !initialDomainName) {
        return (React.createElement("div", null, React.createElement(Typography, { variant: "h6" }, "Error loading Transaction Type: No Transaction type provided")));
    }
    // IMPORTANT: If no Catalog is promoted for product application, the page will not load
    if (!transactionType || catalogObjectLoading || loading) {
        return (React.createElement("div", { className: "udp-transaction-page-loading" }, React.createElement(CircularProgress, { size: 64 })));
    }
    return (React.createElement(React.Fragment, null, calendarViewEnabled && showCalendarView ? (React.createElement(UdpTransactionCalendar, { transactionTypeId: transactionType === null || transactionType === void 0 ? void 0 : transactionType.transactionTypeId, domainName: domainName, searchMethodObject: searchMethodObject, calendarViewConfiguration: calendarViewConfiguration, openWorkflowActionTransaction: (transaction) => {
            handleSidesheet('action', true, transaction);
        }, handleCalendarApiCallback: handleCalendarApiCallback, openAddTransaction: () => {
            handleSidesheet('add', true);
        }, gridTitle: gridTitle, hideCreateTransaction: hideCreateTransaction, onShowGridView: () => setShowCalendarView(false) })) : (React.createElement(UdpTransactionGrid, { transactionTypeId: transactionType === null || transactionType === void 0 ? void 0 : transactionType.transactionTypeId, transactionType: transactionType, domainName: domainName, transactionTypeLoading: transactionTypeLoading, searchMethodObject: searchMethodObject, domainColumnFormatters: domainColumnFormatters, catalogObject: catalogObject, openAddTransaction: () => {
            handleSidesheet('add', true);
        }, openViewTransaction: (transaction) => {
            handleSidesheet('view', true, transaction);
        }, openEditTransaction: (transaction) => {
            handleSidesheet('edit', true, transaction);
        }, openAttachmentTransaction: (transaction) => {
            handleSidesheet('attachment', true, transaction, 1000);
        }, openWorkflowActionTransaction: (transaction) => {
            handleSidesheet('action', true, transaction);
        }, openCreateRevision: (transaction) => {
            handleSidesheet('createRevision', true, transaction);
        }, handleGridApiCallback: handleGridApiCallback, refreshGridData: refreshGridData, gridApi: gridApi, initialFilterModel: filterModel, initialGridOptions: gridOptions, gridTitle: gridTitle, hideCreateTransaction: hideCreateTransaction, columnDefProperties: columnDefProperties, customActions: customActions, paginationAutoPageSize: paginationAutoPageSize, calendarViewEnabled: calendarViewEnabled, onShowCalendarView: () => setShowCalendarView(true) })), React.createElement(UdpTransactionSidesheet, Object.assign({ openStates: sidesheetState, handleSidesheet: handleSidesheet, handleAttachmentTransaction: handleAttachmentTransaction, transaction: selectedTransaction, transactionTypeId: transactionType === null || transactionType === void 0 ? void 0 : transactionType.transactionTypeId, domainName: domainName, refreshGridData: refreshGridData, catalogObject: catalogObject }, sideSheetProps))));
};
export default UdpTransactionsPage;
//# sourceMappingURL=UdpTransactionsPage.js.map