import React, { useMemo, useState, useCallback, useEffect } from 'react';
import { StatusCircleCheckmarkIcon, ErrorIcon, DownloadIcon } from '@fluentui/react-icons';
import { getSanitizedName } from '../../utilities/entities/entityUtilities';
import { FluentDialog } from '../../UI/feedback/FluentDialog';
import { EmptyStateDisplay } from '../../UI/dataDisplay/EmptyStateDisplay';
import { useAxiosGet } from '../../utilities/useAxiosGet';
import { ActionsRenderer } from '../../UI/templates/ui/renderers/ActionsRenderer';
import { AmbientAlert } from '../../UI/feedback/AmbientAlert';
import { TableContainer } from '../../maintenanceEngine/tableBrowser/TableContainer';
import { StatusCellRenderer } from '../../UI/templates/ui/renderers/StatusCellRenderer';
import { useUser } from '../../utilities/auth/useUser';
import { AmbientAutoComplete } from '../../UI/inputs/textField/AmbientAutoComplete';
import { executeQueryWithParameters } from '../utilities/methodUtils';
import { useHandleAxiosSnackbar } from '../../utilities/apiHelpers';
import { ConfigService } from '../../configService';
export const MyExportsPage = (props) => {
    var _a, _b, _c;
    const { productId } = props;
    const user = useUser();
    const [product, setProduct] = useState();
    const [downloadLinkLoading, setDownloadLinkLoading] = useState(false);
    const [fileResultData, setFileResultData] = useState();
    const [downloadOpen, setDownloadOpen] = useState(false);
    const [noDownloadMethod, setNoDownloadMethod] = useState(false);
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const [{ data: products, loading: productsLoading }] = useAxiosGet(ConfigService.tenantV2ApiUrl, `tenant/products?tenantId=${user === null || user === void 0 ? void 0 : user.currentTenantId}&isSubscribable=${!((_a = user === null || user === void 0 ? void 0 : user.can) === null || _a === void 0 ? void 0 : _a.CAN_MANAGE_CATALOGS_FOR_UNSUBSCRIBABLE_PRODUCTS)}`, {}, !user);
    const [{ data: apiCatalog, loading: catalogLoading, error: catalogError }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `tenantProductApiCatalogBase/tenant/${user === null || user === void 0 ? void 0 : user.currentTenantId}/product/${productId ? productId : product === null || product === void 0 ? void 0 : product.productId}`, {}, !(product || productId), false);
    const [{ data: udpJobEntity, loading: jobEntityLoading }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `apicatalog/${apiCatalog === null || apiCatalog === void 0 ? void 0 : apiCatalog.apiCatalogId}/promotedMethodEntities/udpJob/product/${apiCatalog === null || apiCatalog === void 0 ? void 0 : apiCatalog.productId}?compareSanitizedName=true`, {}, !(apiCatalog === null || apiCatalog === void 0 ? void 0 : apiCatalog.productId) || !(apiCatalog === null || apiCatalog === void 0 ? void 0 : apiCatalog.apiCatalogId), false);
    const refetchfileResultData = useCallback(async (selectedRecord) => {
        var _a, _b;
        if ((_a = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetFileResultMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId) {
            setDownloadLinkLoading(true);
            await executeQueryWithParameters({
                data: { JobId: selectedRecord === null || selectedRecord === void 0 ? void 0 : selectedRecord.id }
            }, (_b = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetFileResultMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId)
                .then((res) => {
                setFileResultData(res.data);
            })
                .catch((err) => { });
            setDownloadLinkLoading(false);
        }
        else {
            setNoDownloadMethod(true);
        }
    }, [(_b = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseGetFileResultMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId]);
    const handleSelectRecord = useCallback((data) => {
        refetchfileResultData(data);
        setDownloadOpen(true);
    }, [refetchfileResultData]);
    const getOptionLabel = (val) => {
        return val === null || val === void 0 ? void 0 : val.name;
    };
    const handleProductChange = useCallback((val) => {
        setProduct(val);
    }, []);
    const handleFileDownload = useCallback(() => {
        if (fileResultData === null || fileResultData === void 0 ? void 0 : fileResultData.link) {
            const link = document.createElement('a');
            link.href = fileResultData === null || fileResultData === void 0 ? void 0 : fileResultData.link;
            link.download = '';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            setDownloadOpen(false);
            handleSuccessSnackbar('File successfully downloaded');
        }
    }, [fileResultData === null || fileResultData === void 0 ? void 0 : fileResultData.link, handleSuccessSnackbar]);
    const getJobStatus = (value) => {
        if (value === 1) {
            return null;
        }
        else if (value === 2) {
            return 'info';
        }
        else if (value === 3) {
            return 'success';
        }
        else if (value === 4) {
            return 'error';
        }
    };
    const getJobLabel = (value) => {
        if (value === 1) {
            return 'Pending';
        }
        else if (value === 2) {
            return 'Running';
        }
        else if (value === 3) {
            return 'Completed';
        }
        else if (value === 4) {
            return 'Failed';
        }
    };
    useEffect(() => {
        if (catalogError) {
            handleErrorSnackbar('', 'Error fetching catalog for the selected product');
        }
    }, [catalogError, handleErrorSnackbar]);
    const filterElements = useMemo(() => {
        return [
            {
                searchField: 'jobTypeId',
                searchOperator: '=',
                searchValue: 2
            }
        ];
    }, []);
    const actionList = useMemo(() => {
        return [
            {
                id: 1,
                title: 'Download',
                icon: DownloadIcon,
                onClick: handleSelectRecord,
                disabled: false,
                checkDisabled: (value) => (value === null || value === void 0 ? void 0 : value.statusId) !== 3
            }
        ];
    }, [handleSelectRecord]);
    const columnDefs = useMemo(() => [
        {
            headerName: 'Id',
            sortable: true,
            field: 'id',
            suppressMenu: true
        },
        {
            headerName: 'Name',
            sortable: false,
            field: 'name',
            minWidth: 140,
            suppressMenu: true,
            valueFormatter: (data) => getSanitizedName(data.data.name)
        },
        {
            headerName: 'Date',
            sortable: false,
            valueFormatter: (data) => new Date(data.data.startTime).toLocaleString(),
            minWidth: 130,
            suppressMenu: true
            //sort: 'desc',
        },
        {
            headerName: 'Status',
            field: 'statusId',
            wrapText: true,
            autoHeight: true,
            sortable: false,
            cellRenderer: 'statusCellRenderer',
            cellRendererParams: { getStatus: getJobStatus, getLabel: getJobLabel },
            minWidth: 130,
            maxWidth: 130,
            suppressMenu: true
        },
        {
            headerName: 'Actions',
            filter: false,
            pinned: 'right',
            cellRenderer: 'actionsRenderer',
            width: 120,
            maxWidth: 120,
            cellRendererParams: {
                actionList: actionList,
                value: (data) => data
            },
            suppressMenu: true,
            sortable: false,
            cellStyle: { display: 'flex', alignItems: 'center' }
        }
    ], [actionList]);
    return (React.createElement("div", null, udpJobEntity && !((_c = udpJobEntity === null || udpJobEntity === void 0 ? void 0 : udpJobEntity.unityBaseSearchMethod) === null || _c === void 0 ? void 0 : _c.apiMethodId) && (React.createElement(AmbientAlert, { alertMessage: "UdpJob's search method must be promoted", showAlert: true, alertSeverity: 'error' })), !productId && (React.createElement("div", { style: { margin: '0px 5px 5px 5px' } }, React.createElement(AmbientAutoComplete, { isMultiple: false, id: 'product', name: 'product', label: "Product", onChange: handleProductChange, options: products, size: "small", getOptionLabelFunction: getOptionLabel, value: product, required: true }))), React.createElement(TableContainer, { loading: productsLoading || catalogLoading || jobEntityLoading, title: `Exports`, isServerSide: true, eagerLoad: false, logicalSearchOperator: 2, promotedEntity: udpJobEntity, filterElements: filterElements, actionList: actionList, customColumnDefs: columnDefs, frameworkComponents: {
            statusCellRenderer: StatusCellRenderer,
            actionsRenderer: ActionsRenderer
        }, hideSearchBar: true, hiddenActionButtons: [
            'saveView',
            'views',
            'insights',
            'importExport',
            'group',
            'filter',
            'columns',
            'clearFilters',
            'fitGrid',
            'expandGrid'
        ], height: 'calc(100vh - 167px)', dynamicSizing: true }), React.createElement(FluentDialog, { actionOne: handleFileDownload, actionTwo: () => setDownloadOpen(false), labelOne: "Download", labelTwo: "Cancel", open: downloadOpen, handleClose: () => setDownloadOpen(false), disableOne: noDownloadMethod || downloadLinkLoading, progress: downloadLinkLoading, fullWidth: true }, noDownloadMethod ? (React.createElement(AmbientAlert, { alertMessage: "UdpJob's get file result method must be promoted", showAlert: true, alertSeverity: 'error' })) : downloadLinkLoading ? (React.createElement(EmptyStateDisplay, { primaryText: 'Fetching download link...' })) : (React.createElement(EmptyStateDisplay, { icon: noDownloadMethod ? ErrorIcon : StatusCircleCheckmarkIcon, primaryText: !noDownloadMethod && 'File is ready to download!' })))));
};
export default MyExportsPage;
//# sourceMappingURL=MyExportsPage.js.map