import React, { useEffect, useState, useMemo, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { CrudBrowserContainer } from '../../../maintenanceEngine/crudBrowser/CrudBrowserContainer';
import { CrudTableSidePanel } from '../../../maintenanceEngine/crudBrowser/CrudTableSidePanel';
import { getPathObject, getPrimaryKeyValues } from '../../../utilities/maintenanceEngine/CrudBrowserUtilities';
import { apiMutate } from '../../../utilities/useAxiosMutate';
import { toLowerFirstChar, toUpperFirstChar } from '../../../utilities/input/StringUtilities';
import { CardinalityTypeEnums, EntityAttributeEnums, UdpEnums } from '../../../enums/unitySystemEnums';
import { executeQueryAdHoc } from '../../utilities/methodUtils';
import { getSearchObject } from '../../../utilities/search/SearchUtilities';
import { useHandleAxiosSnackbar } from '../../../utilities/apiHelpers';
import { usePromotedMethodEntity } from '../../../hooks/usePromotedMethodEntity';
import { getSanitizedName } from '../../../utilities/entities/entityUtilities';
import { Alert } from '@material-ui/lab';
import { v4 as uuid } from 'uuid';
import { useLocation } from 'react-router-dom';
import { TagEnums } from '../../../enums/tagEnums';
import { ConfigService } from '../../../configService';
import { SideSheet } from '../../../UI/surfaces/SideSheet';
import { FluentDialog } from '../../../UI/feedback/FluentDialog';
import { useCatalogStore } from '../../../stores/catalogStore';
import { useHistory } from 'react-router-dom';
import { Inquiry } from '../../../inquiry';
import { useAxiosGet } from '../../../utilities';
export const UdpMaintenanceEnginePage = (props) => {
    var _a, _b, _c, _d, _e, _f;
    const { catalogKey, params } = props;
    const { t } = useTranslation();
    const [udpFieldInfos, setUdpFieldInfos] = useState([]);
    const [alertWarnings, setAlertWarnings] = useState([]);
    const [showBackToTableBrowser, setShowBackToTableBrowser] = useState(false);
    const gridApiRef = useRef(null);
    const [modalConfig, setModalConfig] = useState({ type: null, data: null });
    const location = useLocation();
    const state = location.state;
    const history = useHistory();
    let searchParamStr = location.search;
    let searchParams = new URLSearchParams(searchParamStr);
    const searchParamsEntityName = (state === null || state === void 0 ? void 0 : state.entityName)
        ? state.entityName
        : searchParams.has('entityName') === true
            ? toUpperFirstChar(searchParams.get('entityName'))
            : '';
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const handleGoToTableBrowser = useCallback(() => {
        history.push({
            pathname: `/tableBrowser`
        });
    }, [history]);
    const udpCatalogKey = useMemo(() => {
        if ((params === null || params === void 0 ? void 0 : params.entityName) || catalogKey || searchParamsEntityName) {
            return (params === null || params === void 0 ? void 0 : params.entityName) || catalogKey || searchParamsEntityName;
        }
        else {
            handleGoToTableBrowser();
        }
    }, [
        params === null || params === void 0 ? void 0 : params.entityName,
        catalogKey,
        searchParamsEntityName,
        handleGoToTableBrowser
    ]);
    const udpTagId = (params === null || params === void 0 ? void 0 : params.udpTagId) || '';
    const [selectedEntity, setSelectedEntity] = useState(null);
    const [foreignKeyData, setForeignKeyData] = useState(null);
    const [udpFieldSearchApiId, setUdpFieldSearchApiId] = useState(null);
    const [entityUdpObjectInfo, setEntityUdpObjectInfo] = useState(null);
    const [entityName, setEntityName] = useState(null);
    const { currentApiCatalogId } = useCatalogStore();
    const { data: udpObjectInfoEntity } = usePromotedMethodEntity('udpObjectInfo', true);
    const { data: udpObjectFieldInfo } = usePromotedMethodEntity('UdpObjectFieldInfo', true);
    const { data: promotedMethodEntities } = usePromotedMethodEntity(udpCatalogKey, true);
    // 2. MODAL HANDLERS: Callbacks to open and close modals/sheets.
    const openModal = useCallback((type, data = null) => {
        setModalConfig({ type, data });
    }, []);
    const closeModal = useCallback(() => {
        setModalConfig({ type: null, data: null });
    }, []);
    //------- CRUD operations--------
    const executeCreate = useCallback(async (data) => {
        var _a;
        return apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${(_a = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseCreateMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId}`, {
            method: 'post'
        }, data);
    }, [selectedEntity]);
    const executeUpdate = useCallback(async (data) => {
        var _a;
        return apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${(_a = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseUpdateMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId}`, {
            method: 'post'
        }, data);
    }, [selectedEntity]);
    const executeDelete = useCallback(async (data) => {
        var _a;
        return apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${(_a = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseDeleteMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId}`, {
            method: 'post'
        }, data);
    }, [selectedEntity]);
    const onCreate = useCallback(async (data) => {
        return await executeCreate(data);
    }, [executeCreate]);
    const onUpdate = useCallback(async (data) => {
        return await executeUpdate(data);
    }, [executeUpdate]);
    const onDelete = useCallback(async (data) => {
        return await executeDelete(data);
    }, [executeDelete]);
    const [{ data: catalogObject }] = useAxiosGet(ConfigService.integrationV2ApiUrl, `apiCatalog/${currentApiCatalogId}/catalogObject/${entityName}`, {}, !!!currentApiCatalogId || !!!entityName, false);
    const searchFilterElements = useMemo(() => {
        var _a;
        const filterElements = [];
        if (udpTagId) {
            filterElements.push({
                searchField: 'UdpTags.UdpTagAssociationUdpTag.Id',
                searchOperator: '=',
                searchValue: udpTagId
            });
        }
        if (params === null || params === void 0 ? void 0 : params.filterElements) {
            (_a = params === null || params === void 0 ? void 0 : params.filterElements) === null || _a === void 0 ? void 0 : _a.forEach((filter) => {
                filterElements.push(filter);
            });
        }
        return filterElements;
    }, [udpTagId, params === null || params === void 0 ? void 0 : params.filterElements]);
    const entityAttributes = useMemo(() => {
        if ((udpFieldInfos === null || udpFieldInfos === void 0 ? void 0 : udpFieldInfos.length) > 0 && catalogObject && entityName) {
            // 1. Get original attributes from catalog
            const originalAttributes = (catalogObject === null || catalogObject === void 0 ? void 0 : catalogObject.properties) || [];
            const attributeMap = new Map(originalAttributes.map((attr) => [attr.name.toLowerCase(), attr]));
            // 2. Create the sorted list by iterating through udpFieldInfos
            const sortedPart = udpFieldInfos
                .map((field) => {
                const match = attributeMap.get(field.name.toLowerCase());
                if (match) {
                    // Merge properties as we build the sorted list
                    return Object.assign(Object.assign({}, match), { extendedProperties: Object.assign(Object.assign({}, match.extendedProperties), { udpFieldProperties: field.properties }) });
                }
                return null;
            })
                .filter(Boolean);
            // 3. Find unmatched items in a single pass
            const udpFieldNames = new Set(udpFieldInfos.map((f) => f.name.toLowerCase()));
            const unmatchedPart = originalAttributes.filter((attr) => !udpFieldNames.has(attr.name.toLowerCase()));
            // 4. Combine the sorted, merged part with the original unmatched part
            return [...sortedPart, ...unmatchedPart];
        }
    }, [catalogObject, entityName, udpFieldInfos]);
    const getMetaDataForUdpField = useCallback(async (entityName) => {
        let fieldInfos = [];
        if (udpFieldSearchApiId) {
            const filterElements = [
                {
                    searchField: 'ObjectInfo.SanitizedName',
                    searchOperator: '=',
                    searchValue: getSanitizedName(entityName)
                }
            ];
            const requestObj = getSearchObject(filterElements, 1, 50, true);
            await executeQueryAdHoc({ data: requestObj }, udpFieldSearchApiId).then((resp) => {
                var _a;
                fieldInfos = (_a = resp.data) === null || _a === void 0 ? void 0 : _a.pageList;
            });
        }
        return fieldInfos;
    }, [udpFieldSearchApiId]);
    const getFKMethodEntities = useCallback(async (attributes) => {
        var _a;
        if (!attributes) {
            return [];
        }
        let fkMethods = [];
        for (const attr of attributes) {
            // check if there is a property with this childEntity
            if ((_a = attr === null || attr === void 0 ? void 0 : attr.extendedProperties) === null || _a === void 0 ? void 0 : _a.childEntity) {
                // get the list of child entity field names from the Keys array
                const ceFieldsArr = [];
                const childAssoc = attr.extendedProperties.childEntityAssoc;
                if (childAssoc &&
                    Object.keys(childAssoc).length > 0 &&
                    (childAssoc.Cardinality === CardinalityTypeEnums.Many_To_Many ||
                        childAssoc.Cardinality === CardinalityTypeEnums.One_To_Many) &&
                    !childAssoc.UdpType) {
                    childAssoc.Keys.forEach((value, i) => {
                        const name = value.split(',')[0];
                        if (name) {
                            ceFieldsArr.push({
                                idx: i,
                                name: /^[A-Z]*$/.test(name)
                                    ? name.toLowerCase()
                                    : toLowerFirstChar(name)
                            });
                        }
                    });
                }
                // find the child entity attribute
                const ceAttr = attributes.find((p) => ceFieldsArr.find((cef) => cef.name === p.name));
                if (ceAttr) {
                    // get list of entity if ceProp exists
                    await apiMutate(ConfigService.integrationV1ApiUrl, `apicatalog/${currentApiCatalogId}/promotedMethodEntities/${attr.reference}/product/${ConfigService.config.UNITY_PRODUCT_ID}`, {
                        method: 'get'
                    }, {}).then((resp) => {
                        if (resp && resp.data) {
                            fkMethods.push({
                                entityAttribute: ceAttr,
                                entity: resp.data
                            });
                        }
                    });
                }
            }
        }
        return fkMethods;
    }, [currentApiCatalogId]);
    const getFKAssociationLabel = useCallback(async (entityName) => {
        let fieldsInfo = [];
        fieldsInfo = await getMetaDataForUdpField(entityName);
        if ((fieldsInfo === null || fieldsInfo === void 0 ? void 0 : fieldsInfo.length) <= 0) {
            return '';
        }
        const associationLabelInfo = fieldsInfo === null || fieldsInfo === void 0 ? void 0 : fieldsInfo.find((fi) => {
            var _a, _b;
            return ((_b = (_a = fi.properties) === null || _a === void 0 ? void 0 : _a.maintainenceConfig) === null || _b === void 0 ? void 0 : _b.associationLabel) === 'true';
        });
        return associationLabelInfo === null || associationLabelInfo === void 0 ? void 0 : associationLabelInfo.name;
    }, [getMetaDataForUdpField]);
    const getDataByKey = (obj, k) => {
        var _a;
        if (!obj)
            return null;
        let val = (_a = obj[k]) !== null && _a !== void 0 ? _a : null;
        if (!val) {
            const key = Object.keys(obj).find((objKey) => objKey.toLowerCase().includes(k));
            if (key) {
                val = obj[key];
            }
        }
        return val;
    };
    const getFKData = useCallback(async () => {
        var _a, _b, _c, _d, _e;
        if (!(entityAttributes === null || entityAttributes === void 0 ? void 0 : entityAttributes.length)) {
            return null;
        }
        const fkMethods = await getFKMethodEntities(entityAttributes);
        if (!(fkMethods === null || fkMethods === void 0 ? void 0 : fkMethods.length)) {
            setForeignKeyData([]);
            return [];
        }
        let fkData = [];
        let promises = [];
        let promiseDetails = [];
        const warnings = [];
        for (const method of fkMethods) {
            if (method && ((_a = method === null || method === void 0 ? void 0 : method.entity) === null || _a === void 0 ? void 0 : _a.unityBaseGetAllMethod)) {
                const associationLabel = await getFKAssociationLabel(method.entity.entityName);
                promiseDetails.push({
                    url: ConfigService.integrationV1ApiUrl +
                        `/apimethod/executeQueryWithParameters/${(_c = (_b = method === null || method === void 0 ? void 0 : method.entity) === null || _b === void 0 ? void 0 : _b.unityBaseGetAllMethod) === null || _c === void 0 ? void 0 : _c.apiMethodId}`,
                    fieldName: method.entityAttribute.name,
                    name: method.entity.entityName,
                    associationLabel: associationLabel
                });
                promises.push(apiMutate(ConfigService.integrationV1ApiUrl, `apimethod/executeQueryWithParameters/${(_e = (_d = method === null || method === void 0 ? void 0 : method.entity) === null || _d === void 0 ? void 0 : _d.unityBaseGetAllMethod) === null || _e === void 0 ? void 0 : _e.apiMethodId}`, {
                    method: 'post'
                }, { data: {} }));
            }
            else {
                warnings.push({
                    id: uuid(),
                    message: `${method.entity.entityName}'s Get-All method needs to be promoted`
                });
            }
        }
        setAlertWarnings((existingWarnings) => [...existingWarnings, ...warnings]);
        Promise.all(promises).then((resp) => {
            resp.forEach((response, index) => {
                if (response.status === 200) {
                    if (response === null || response === void 0 ? void 0 : response.data) {
                        let respData = [];
                        const promiseDetail = promiseDetails.find((p) => {
                            var _a;
                            return p.url === ((_a = response === null || response === void 0 ? void 0 : response.config) === null || _a === void 0 ? void 0 : _a.url) &&
                                !fkData.find((fd) => fd.entityName === p.name && fd.fieldName === p.fieldName);
                        });
                        response.data.forEach((d) => {
                            const idName = (promiseDetail === null || promiseDetail === void 0 ? void 0 : promiseDetail.fieldName) && d[promiseDetail.fieldName]
                                ? promiseDetail.fieldName
                                : 'id';
                            const id = getDataByKey(d, idName);
                            const name = getDataByKey(d, (promiseDetail === null || promiseDetail === void 0 ? void 0 : promiseDetail.associationLabel)
                                ? toLowerFirstChar(promiseDetail.associationLabel)
                                : 'name');
                            respData.push({ id: id, name: name !== null && name !== void 0 ? name : id });
                        });
                        if (!!promiseDetail) {
                            fkData.push({
                                fieldName: promiseDetail.fieldName,
                                entityName: promiseDetail.name,
                                name: promiseDetail.fieldName,
                                data: respData
                            });
                        }
                    }
                }
            });
            setForeignKeyData(fkData);
        });
    }, [entityAttributes, getFKMethodEntities, getFKAssociationLabel]);
    const handleOnCreate = useCallback(async (values) => {
        if (selectedEntity) {
            const entityName = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.entityName;
            if (selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseCreateMethod) {
                const data = { requestBody: values };
                const response = await onCreate({ data }).catch((res) => {
                    handleErrorSnackbar(res);
                });
                if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
                    handleSuccessSnackbar(entityName
                        ? t(`${entityName} has been created`)
                        : t(`Entity has been created`));
                    gridApiRef.current.refreshServerSide();
                    closeModal('create');
                    return response;
                }
            }
            else {
                handleErrorSnackbar(null, selectedEntity.entityName + "'s create method must be promoted");
            }
        }
    }, [
        selectedEntity,
        onCreate,
        handleErrorSnackbar,
        handleSuccessSnackbar,
        t,
        closeModal
    ]);
    const handleOnUpdate = useCallback(async (values, primaryKeyValues) => {
        if (selectedEntity) {
            const entityName = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.entityName;
            if (selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseUpdateMethod) {
                // Get primary key value object using path parameters and merge with data
                const pathObject = getPathObject(selectedEntity.unityBaseUpdateMethod.pathParameters, primaryKeyValues);
                let data = { requestBody: values };
                if (Array.isArray(pathObject)) {
                    pathObject.forEach((po) => {
                        data[Object.keys(po)[0]] = po[Object.keys(po)[0]];
                    });
                }
                else {
                    data = Object.assign(Object.assign({}, pathObject), { requestBody: values });
                }
                const response = await onUpdate({ data }).catch((res) => {
                    handleErrorSnackbar(res);
                });
                if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
                    handleSuccessSnackbar(entityName
                        ? t(`${entityName} has been updated`)
                        : t(`Entity has been updated`));
                    gridApiRef.current.refreshServerSide();
                    closeModal('edit');
                }
            }
        }
    }, [
        selectedEntity,
        onUpdate,
        handleErrorSnackbar,
        handleSuccessSnackbar,
        t,
        closeModal
    ]);
    const handleOnDelete = useCallback(async (value) => {
        if (selectedEntity) {
            const entityName = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.entityName;
            if (selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseDeleteMethod) {
                // Get primary key value object using path parameters and merge with data
                const primaryKeyValues = getPrimaryKeyValues(entityAttributes, value);
                const pathObject = getPathObject(selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseDeleteMethod.pathParameters, primaryKeyValues);
                let data = {};
                if (Array.isArray(pathObject)) {
                    pathObject.forEach((po) => {
                        data[Object.keys(po)[0]] = po[Object.keys(po)[0]];
                    });
                }
                else {
                    data = Object.assign({}, pathObject);
                }
                const response = await onDelete({ data }).catch((res) => {
                    handleErrorSnackbar(res);
                });
                if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
                    handleSuccessSnackbar(entityName
                        ? t(`${entityName} has been deleted`)
                        : t(`Entity has been deleted`));
                    gridApiRef.current.refreshServerSide();
                    closeModal('delete');
                }
            }
        }
    }, [
        selectedEntity,
        entityAttributes,
        onDelete,
        handleErrorSnackbar,
        handleSuccessSnackbar,
        t,
        closeModal
    ]);
    const removeWarning = useCallback((id) => {
        const updatedWarnings = alertWarnings.filter((warning) => warning.id !== id);
        setAlertWarnings(updatedWarnings);
    }, [alertWarnings]);
    const shouldDisableAction = useCallback((value) => {
        const sanitizedEntityName = getSanitizedName(entityName);
        const tagTypeShouldDisableEdit = [TagEnums.TagTypeSanitizedName.toLowerCase()].includes(sanitizedEntityName === null || sanitizedEntityName === void 0 ? void 0 : sanitizedEntityName.toLowerCase()) && !(value === null || value === void 0 ? void 0 : value[toLowerFirstChar(EntityAttributeEnums.User_Defined)]);
        const shortCutContentShouldDisableEdit = [UdpEnums.Udp_Shortcut_Content.toLowerCase()].includes(sanitizedEntityName === null || sanitizedEntityName === void 0 ? void 0 : sanitizedEntityName.toLowerCase()) &&
            (value === null || value === void 0 ? void 0 : value[toLowerFirstChar(EntityAttributeEnums.Is_Product_ShortcutContent)]);
        const lookupShouldDisableEdit = [UdpEnums.Udp_Lookup.toLowerCase()].includes(sanitizedEntityName === null || sanitizedEntityName === void 0 ? void 0 : sanitizedEntityName.toLowerCase()) && (value === null || value === void 0 ? void 0 : value[toLowerFirstChar(EntityAttributeEnums.Is_Product_Lookup)]);
        return (tagTypeShouldDisableEdit ||
            shortCutContentShouldDisableEdit ||
            lookupShouldDisableEdit);
    }, [entityName]);
    const actionList = useMemo(() => {
        if (!selectedEntity) {
            return [];
        }
        let actions = [
            {
                id: 'edit',
                iconName: 'edit', // Pass string name for the icon
                getTitle: () => 
                // Use getTitle for dynamic text
                (selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseUpdateMethod)
                    ? t('Edit')
                    : t('Edit Method Not Accessible'),
                handleOnClick: (e, params) => {
                    openModal('edit', params.data); // Calls parent state handler
                },
                checkDisabled: (params) => !!!(selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseUpdateMethod) ||
                    shouldDisableAction(params.data)
            },
            {
                id: 'delete',
                iconName: 'trashCan', // Pass string name for the icon
                getTitle: () => (selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseDeleteMethod)
                    ? t('Delete')
                    : t('Delete Method Not Accessible'),
                handleOnClick: (e, params) => {
                    openModal('delete', params.data); // Calls parent state handler
                },
                checkDisabled: (params) => !!!(selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseDeleteMethod) ||
                    shouldDisableAction(params.data)
            }
        ];
        if (params === null || params === void 0 ? void 0 : params.inquiryTreeId) {
            actions.splice(1, 0, {
                id: 'inquiry',
                iconName: 'relationshipDiagram',
                title: 'Detailed view',
                handleOnClick: (e, params) => {
                    openModal('inquiry', params.data);
                }
            });
        }
        return actions;
    }, [
        selectedEntity,
        t,
        shouldDisableAction,
        openModal,
        params === null || params === void 0 ? void 0 : params.inquiryTreeId
    ]);
    useEffect(() => {
        var _a;
        const executeSearchForEntityUdpObjectInfo = async (apiMethodId, sanitizedEntityName) => {
            var _a;
            const filterElements = [
                {
                    searchField: 'SanitizedName',
                    searchOperator: '=',
                    searchValue: sanitizedEntityName
                }
            ];
            const requestObj = getSearchObject(filterElements, 1, 50, false);
            const response = await executeQueryAdHoc({ data: requestObj }, apiMethodId);
            if (response.status === 200) {
                const data = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.pageList[0];
                setEntityUdpObjectInfo(data);
            }
        };
        if ((udpObjectInfoEntity === null || udpObjectInfoEntity === void 0 ? void 0 : udpObjectInfoEntity.unityBaseSearchMethod) && entityName) {
            executeSearchForEntityUdpObjectInfo((_a = udpObjectInfoEntity === null || udpObjectInfoEntity === void 0 ? void 0 : udpObjectInfoEntity.unityBaseSearchMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId, getSanitizedName(entityName));
        }
    }, [udpObjectInfoEntity, entityName]);
    useEffect(() => {
        const setFrKeyData = async () => {
            await getFKData();
        };
        if (entityAttributes && udpFieldSearchApiId !== null) {
            setFrKeyData();
        }
    }, [entityAttributes, getFKData, udpFieldSearchApiId]);
    useEffect(() => {
        if (promotedMethodEntities) {
            setSelectedEntity(promotedMethodEntities);
            setEntityName(promotedMethodEntities === null || promotedMethodEntities === void 0 ? void 0 : promotedMethodEntities.entityName);
        }
    }, [promotedMethodEntities]);
    useEffect(() => {
        var _a, _b;
        if (udpObjectFieldInfo) {
            if ((_a = udpObjectFieldInfo === null || udpObjectFieldInfo === void 0 ? void 0 : udpObjectFieldInfo.unityBaseSearchMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId) {
                setUdpFieldSearchApiId((_b = udpObjectFieldInfo === null || udpObjectFieldInfo === void 0 ? void 0 : udpObjectFieldInfo.unityBaseSearchMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId);
            }
            else {
                setUdpFieldSearchApiId('');
                const udpFieldWarning = {
                    id: uuid(),
                    message: `UdpObjectFieldInfo method needs to be promoted`
                };
                setAlertWarnings((prevState) => [...prevState, udpFieldWarning]);
            }
        }
    }, [udpObjectFieldInfo]);
    useEffect(() => {
        const setFieldInfos = async () => {
            let temp = await getMetaDataForUdpField(entityName);
            setUdpFieldInfos(temp);
        };
        if (udpFieldSearchApiId) {
            setFieldInfos();
        }
    }, [
        udpObjectFieldInfo,
        getMetaDataForUdpField,
        udpFieldSearchApiId,
        entityName
    ]);
    useEffect(() => {
        var _a;
        if (((_a = location.state) === null || _a === void 0 ? void 0 : _a.from) === 'tablebrowser') {
            setShowBackToTableBrowser(true);
        }
    }, [location.state]);
    const handleGridApiCallback = (api) => {
        gridApiRef.current = api;
    };
    const primaryKeyFieldName = useMemo(() => {
        var _a, _b;
        const fieldName = (_a = udpFieldInfos === null || udpFieldInfos === void 0 ? void 0 : udpFieldInfos.find((field) => field.isPrimaryKey)) === null || _a === void 0 ? void 0 : _a.name;
        return ((_b = fieldName === null || fieldName === void 0 ? void 0 : fieldName[0]) === null || _b === void 0 ? void 0 : _b.toLowerCase()) + (fieldName === null || fieldName === void 0 ? void 0 : fieldName.slice(1));
    }, [udpFieldInfos]);
    return (React.createElement(React.Fragment, null, alertWarnings.map((warning) => (React.createElement(Alert, { key: warning.id, onClose: () => removeWarning(warning.id), severity: "warning" }, warning.message || ''))), React.createElement(CrudBrowserContainer, { actionList: actionList, onCreate: () => openModal('create'), entityAttributes: entityAttributes, foreignKeyData: foreignKeyData, promotedEntity: selectedEntity, apiMethod: { currentApiCatalogId, entityName }, filterElements: searchFilterElements, setAlertWarnings: setAlertWarnings, gridApiCallback: handleGridApiCallback, showBackToTableBrowser: showBackToTableBrowser, gridTitle: (_a = entityUdpObjectInfo === null || entityUdpObjectInfo === void 0 ? void 0 : entityUdpObjectInfo.properties) === null || _a === void 0 ? void 0 : _a.displayName }), React.createElement(SideSheet, { open: modalConfig.type === 'create' || modalConfig.type === 'edit', onClose: closeModal, title: modalConfig.type === 'create'
            ? `Add New ${((_b = entityUdpObjectInfo === null || entityUdpObjectInfo === void 0 ? void 0 : entityUdpObjectInfo.properties) === null || _b === void 0 ? void 0 : _b.displayName) ||
                getSanitizedName(entityName)}`
            : `Edit ${((_c = entityUdpObjectInfo === null || entityUdpObjectInfo === void 0 ? void 0 : entityUdpObjectInfo.properties) === null || _c === void 0 ? void 0 : _c.displayName) ||
                getSanitizedName(entityName)}`, width: 600 }, (modalConfig.type === 'create' || modalConfig.type === 'edit') && (React.createElement(CrudTableSidePanel, { entityAttributes: entityAttributes, udpFieldInfos: udpFieldInfos, foreignKeyData: foreignKeyData, closeSideSheet: closeModal, isNewEntry: modalConfig.type === 'create', entityName: entityName, onCreate: modalConfig.type === 'create' ? handleOnCreate : undefined, onUpdate: modalConfig.type === 'edit' ? handleOnUpdate : undefined, crudTableEditionData: modalConfig.type === 'edit' ? modalConfig.data : null, pageId: modalConfig.type === 'edit'
            ? (_d = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseUpdateMethod) === null || _d === void 0 ? void 0 : _d.pageId
            : (_e = selectedEntity === null || selectedEntity === void 0 ? void 0 : selectedEntity.unityBaseCreateMethod) === null || _e === void 0 ? void 0 : _e.pageId }))), React.createElement(SideSheet, { open: modalConfig.type === 'inquiry', onClose: closeModal, title: 'Detailed view', width: '90%' }, React.createElement(Inquiry, { treeId: params === null || params === void 0 ? void 0 : params.inquiryTreeId, autoCollapseNav: true, searchValue: (_f = modalConfig === null || modalConfig === void 0 ? void 0 : modalConfig.data) === null || _f === void 0 ? void 0 : _f[primaryKeyFieldName] })), React.createElement(FluentDialog, { open: modalConfig.type === 'delete', handleClose: closeModal, title: t('Delete'), message: t('Are you sure you want to delete this row?'), actionOne: closeModal, labelOne: t('Cancel'), actionTwo: () => handleOnDelete(modalConfig.data), labelTwo: t('Confirm') })));
};
export default UdpMaintenanceEnginePage;
//# sourceMappingURL=UdpMaintenanceEnginePage.js.map