import React, { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AmbientGridTemplate } from '../../templates/deprecated/AmbientGridTemplate/AmbientGridTemplate';
import { apiMutate } from '../../../utilities/useAxiosMutate';
import { FilterOperators } from '../../../models/SearchOperator';
import { SideSheet } from '../../surfaces/SideSheet';
import { useAgGridApi } from '../../../utilities/aggrid/AgTable';
const SearchSideSheet = props => {
    const { open, handleClose, exclude, title, productApiBase, searchApi, colDefs = [], gridTitle, idField, formIdField, handleSearch, width = '800px', height = '58vh' } = props;
    const [selectedData, setSelectedData] = useState([]);
    const { t } = useTranslation();
    const { gridApi, onGridReady, gridColumnApi } = useAgGridApi();
    const paginationPageSize = 20;
    // TODO: use queryId or new data grid from stencil
    const searchData = useCallback(async data => apiMutate(productApiBase, searchApi, {
        method: 'post',
    }, data), [productApiBase, searchApi]);
    const onSelectionChanged = useCallback(() => {
        var _a;
        const selectedRows = (_a = gridApi === null || gridApi === void 0 ? void 0 : gridApi.getSelectedRows()) !== null && _a !== void 0 ? _a : [];
        setSelectedData(selectedRows);
    }, [gridApi]);
    const handleCloseSideSheet = useCallback(data => {
        handleClose(data);
        setSelectedData([]);
    }, [handleClose]);
    const dataSource = useMemo(() => ({
        getRows: async ({ request, success, fail }) => {
            var _a, _b;
            var _c;
            if (handleSearch) {
                handleSearch(paginationPageSize, request, success, fail);
                return;
            }
            const filterElements = (request === null || request === void 0 ? void 0 : request.filterModel)
                ? (_a = Object.entries(request.filterModel)) === null || _a === void 0 ? void 0 : _a.map(([key, value]) => {
                    return {
                        searchField: key,
                        searchOperator: FilterOperators[value === null || value === void 0 ? void 0 : value.type],
                        searchValue: value === null || value === void 0 ? void 0 : value.filter,
                    };
                })
                : [];
            const orderElements = (request === null || request === void 0 ? void 0 : request.sortModel)
                ? (_b = request.sortModel) === null || _b === void 0 ? void 0 : _b.map(sortObj => {
                    var _a;
                    return {
                        sortColumn: sortObj === null || sortObj === void 0 ? void 0 : sortObj.colId,
                        sortDirection: (_a = sortObj === null || sortObj === void 0 ? void 0 : sortObj.sort) === null || _a === void 0 ? void 0 : _a.toUpperCase(),
                    };
                })
                : [];
            await searchData({
                data: {
                    filterElements: filterElements,
                    orderElements: orderElements,
                    pagesize: paginationPageSize,
                    pageNumber: ((_c = request === null || request === void 0 ? void 0 : request.startRow) !== null && _c !== void 0 ? _c : 0) / paginationPageSize + 1,
                },
            })
                .then(response => {
                var _a, _b;
                success({
                    rowData: (_a = response.data) === null || _a === void 0 ? void 0 : _a.pageList,
                    rowCount: (_b = response.data) === null || _b === void 0 ? void 0 : _b.total,
                });
            })
                .catch(error => {
                fail();
            });
        },
    }), [searchData, handleSearch]);
    return (React.createElement(SideSheet, { open: open, onClose: () => handleCloseSideSheet(), title: title, width: width, buttonLabel: t('Choose'), onSubmit: () => {
            handleCloseSideSheet(selectedData);
        } }, React.createElement(AmbientGridTemplate, { title: gridTitle, rowModelType: "serverSide", serverSideDatasource: dataSource, cacheBlockSize: paginationPageSize, serverSideStoreType: "partial", paginationPageSize: paginationPageSize, columnDefs: [
            {
                field: '',
                checkboxSelection: true,
                maxWidth: 60,
                minWidth: 60,
                cellRenderer: params => {
                    console.log({
                        exclude,
                        formIdField,
                        idField,
                        bool: exclude === null || exclude === void 0 ? void 0 : exclude.find(selectedItem => {
                            var _a;
                            return selectedItem[formIdField] === ((_a = params.data) === null || _a === void 0 ? void 0 : _a[idField]);
                        }),
                    });
                    if ((params === null || params === void 0 ? void 0 : params.data) &&
                        !!(exclude === null || exclude === void 0 ? void 0 : exclude.find(selectedItem => {
                            var _a;
                            return selectedItem[formIdField] === ((_a = params.data) === null || _a === void 0 ? void 0 : _a[idField]);
                        }))) {
                        params.node.setSelected(true);
                    }
                },
            },
            ...colDefs,
        ], hideGroupTab: true, hideColumnTab: true, suppressRowClickSelection: true, onSelectionChanged: onSelectionChanged, rowSelection: "multiple", api: gridApi, gridReady: onGridReady, columnApi: gridColumnApi, dynamicSizing: true, height: height })));
};
export default SearchSideSheet;
//# sourceMappingURL=SearchSideSheet.js.map