import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { makeStyles } from '@material-ui/core';
import { useAgGridApi, AgTable } from '../../utilities/aggrid/AgTable.tsx';
import { useGridFormat, useExport } from '../../utilities/aggrid/GridFunctions.js';
import { PrimaryActionHeader } from '../../UI/utilityDisplay/utilityHeader/PrimaryActionHeader';
import { ServerSideRowModelModule } from '@ag-grid-enterprise/server-side-row-model';
import { camelToPascalCaseWithSpace } from '../../utilities/input/StringUtilities';
import { InquirySearchDatasource } from './InquirySearchDatasource';
import { getSearchIdentifiers } from '../../utilities/search/SearchUtilities';
import { LogicalSearchOperatorEnums } from '../../enums/unitySystemEnums.ts';
import { sortBy } from 'lodash-es';
const useStyles = makeStyles((theme) => ({
    root: {
        height: (props) => {
            var _a, _b, _c, _d;
            var _e;
            const rowCount = ((_b = (_a = props === null || props === void 0 ? void 0 : props.queryData) === null || _a === void 0 ? void 0 : _a.pageList) === null || _b === void 0 ? void 0 : _b.length) > 10
                ? 10
                : (_e = (_d = (_c = props === null || props === void 0 ? void 0 : props.queryData) === null || _c === void 0 ? void 0 : _c.pageList) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0;
            const topResultsOnlyHeight = rowCount * 48 + 60;
            const moreResultsHeight = rowCount * 48 + 116;
            return props.topResultsOnly ? topResultsOnlyHeight : moreResultsHeight;
        }
    }
}));
export const InquirySearchTable = (props) => {
    const { apiMethodId, associatedInquiryTree, catalogReturnObject, catalogObjects, columns, executeQuery, queryColumnsData, isAdvancedSearch, onRowDoubleClick, queryData, searchFilterElements, searchFilterGroups, setSelectedSearchRows, treeStructure, topResultsOnly = false, topResultsSize = 50 } = props;
    const classes = useStyles(props);
    const { gridApi, onGridReady } = useAgGridApi();
    const [agGridOptions] = useState({});
    const [gridFormat] = useGridFormat();
    const [exportGrid] = useExport();
    const searchIdentifier = useMemo(() => {
        const identifiers = getSearchIdentifiers(catalogObjects, catalogReturnObject) || [];
        return identifiers.toString();
    }, [catalogObjects, catalogReturnObject]);
    const columnDefs = useMemo(() => {
        var _a;
        let commonCols = columns.map((column) => {
            var _a, _b;
            let matchingColumnIndex = null;
            const matchingColumn = queryColumnsData.find((c, index) => {
                if (c.name === (column === null || column === void 0 ? void 0 : column.name)) {
                    matchingColumnIndex = index;
                }
                return c.name === (column === null || column === void 0 ? void 0 : column.name);
            });
            let def = {
                headerName: column.alias || camelToPascalCaseWithSpace(column.name),
                field: column.name
                // cellStyle: (params) => ValidateCellStylesByConditionals(params, column)
            };
            if (matchingColumn) {
                def = {
                    headerName: matchingColumn.alias ||
                        camelToPascalCaseWithSpace(matchingColumn.name),
                    field: matchingColumn.name
                };
            }
            if ((_a = column === null || column === void 0 ? void 0 : column.extendedProperties) === null || _a === void 0 ? void 0 : _a.searchable) {
                def = Object.assign(Object.assign({}, def), { filter: 'agTextColumnFilter', filterParams: {
                        suppressAndOrCondition: true,
                        filterOptions: [
                            'equals',
                            'contains',
                            'notEqual',
                            'greaterThan',
                            'lessThan',
                            'greaterThanOrEqual',
                            'lessThanOrEqual'
                        ]
                    }, enableRowGroup: true });
            }
            if ((_b = column === null || column === void 0 ? void 0 : column.extendedProperties) === null || _b === void 0 ? void 0 : _b.orderable) {
                def = Object.assign(Object.assign({}, def), { sortable: true });
            }
            def.hide = !matchingColumn;
            def.index = matchingColumnIndex;
            return def;
        });
        const currentNode = treeStructure.find((node) => {
            var _a;
            return ((_a = node.properties) === null || _a === void 0 ? void 0 : _a.catalogReturnObject) === catalogReturnObject;
        });
        const searchConfiguration = ((_a = currentNode === null || currentNode === void 0 ? void 0 : currentNode.properties) === null || _a === void 0 ? void 0 : _a.searchConfiguration) || null;
        let requiresOrdering = false;
        if (searchConfiguration) {
            requiresOrdering = searchConfiguration.some((config) => !!config.results.trim());
        }
        if (requiresOrdering) {
            // Sort columns using the searchConfiguration results
            const searchConfigWithResults = searchConfiguration.filter((config) => !!config.results);
            commonCols.forEach((col) => {
                col.index = null;
                const foundSearchConfig = searchConfigWithResults.find((config) => config.name === col.field);
                if (foundSearchConfig) {
                    col.index = parseFloat(foundSearchConfig.results);
                }
            });
        }
        // Sort columns
        commonCols = sortBy(commonCols, (col) => col.index);
        return commonCols;
    }, [columns, queryColumnsData, treeStructure, catalogReturnObject]);
    const defaultColDef = useMemo(() => ({
        resizable: true,
        editable: false,
        // filter: true,
        enableValue: true,
        allowedAggFuncs: ['sum', 'min', 'max', 'count', 'avg', 'first', 'last']
    }), []);
    const rowData = useMemo(() => {
        var _a;
        if (!queryData)
            return [];
        return (_a = queryData === null || queryData === void 0 ? void 0 : queryData.pageList) === null || _a === void 0 ? void 0 : _a.slice(0, topResultsSize);
    }, [queryData, topResultsSize]);
    const handleSelectionChanged = useCallback(() => {
        const selectedRows = gridApi.getSelectedRows();
        setSelectedSearchRows(catalogReturnObject, selectedRows, searchIdentifier, apiMethodId, treeStructure, associatedInquiryTree);
    }, [
        gridApi,
        catalogReturnObject,
        setSelectedSearchRows,
        searchIdentifier,
        apiMethodId,
        treeStructure,
        associatedInquiryTree
    ]);
    const handleRowDoubleClicked = useCallback((event) => {
        if (!gridApi)
            return;
        if (onRowDoubleClick) {
            onRowDoubleClick(event.node.data, catalogReturnObject);
        }
    }, [gridApi, onRowDoubleClick, catalogReturnObject]);
    useEffect(() => {
        if (!gridApi)
            return;
        gridApi.sizeColumnsToFit();
        let datasource = InquirySearchDatasource(queryData, apiMethodId, searchFilterElements, isAdvancedSearch
            ? LogicalSearchOperatorEnums.And
            : LogicalSearchOperatorEnums.Or, executeQuery, searchFilterGroups);
        // eslint-disable-next-line no-unused-expressions
        gridApi === null || gridApi === void 0 ? void 0 : gridApi.setServerSideDatasource(datasource);
    }, [
        gridApi,
        apiMethodId,
        searchFilterElements,
        queryData,
        isAdvancedSearch,
        executeQuery,
        searchFilterGroups
    ]);
    return (React.createElement("div", null, !topResultsOnly && (React.createElement(React.Fragment, null, React.createElement(PrimaryActionHeader, { hidePAB: true, 
        // LAA UNT-2624: remove whitespace caused by the action row
        hideActionRow: true, expandAllItems: () => gridFormat(gridApi, 'expand'), collapse: () => gridFormat(gridApi, 'collapse'), resizeGrid: () => gridFormat(gridApi, 'resize'), exportGrid: () => exportGrid(gridApi, 'csv'), grid: true }), React.createElement(AgTable, Object.assign({ className: classes.root, modules: [ServerSideRowModelModule], rowModelType: 'serverSide', serverSideStoreType: 'partial', pagination: true, paginationPageSize: 20, cacheOverflowSize: 2, maxConcurrentDatasourceRequests: 1, cacheBlockSize: 20, onGridReady: onGridReady, columnDefs: columnDefs, defaultColDef: defaultColDef, 
        // getRowNodeId={row => row.channelConfigurationID}
        onRowDoubleClicked: handleRowDoubleClicked, rowSelection: "multiple", rowMultiSelectWithClick: true, onSelectionChanged: handleSelectionChanged, 
        // animateRows={true}
        api: gridApi, dynamicSizing: true }, agGridOptions)))), topResultsOnly && (React.createElement(AgTable, Object.assign({ className: classes.root, rowData: rowData || [], onGridReady: onGridReady, columnDefs: columnDefs, defaultColDef: defaultColDef, 
        // getRowNodeId={row => row.channelConfigurationID}
        onRowDoubleClicked: handleRowDoubleClicked, rowSelection: "multiple", rowMultiSelectWithClick: true, onSelectionChanged: handleSelectionChanged, animateRows: true, api: gridApi, dynamicSizing: true }, agGridOptions)))));
};
//# sourceMappingURL=InquirySearchTable.js.map