import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { makeStyles, Divider, Typography } from '@material-ui/core';
import { SubmitButton } from '../../utilities/form/SubmitButton.tsx';
import { Form } from '../../utilities/form/Form.tsx';
import { FormButtons } from '../../utilities/form/FormButtons.tsx';
import { FluentTextFieldAutoComplete } from '../../UI/inputs/textField/FluentTextFieldAutoComplete';
import { orderBy } from 'lodash-es';
import { InquiryAdvancedSearchForm } from './InquiryAdvancedSearchForm';
import { LookupTypeEnums } from '../../enums/unitySystemEnums.ts';
import { SearchOperators } from '../../models/SearchOperator.ts';
import { FluentIconButton } from '../../UI/inputs/buttons/FluentIconButton';
import { FluentButton } from '../../UI/inputs/buttons/FluentButton';
import { ClearIcon } from '@fluentui/react-icons';
import { getSanitizedName } from '../../utilities/entities/entityUtilities.js';
const useStyles = makeStyles((theme) => ({
    root: {},
    entitySelect: {
        marginRight: theme.spacing(1),
        marginLeft: theme.spacing(1)
    },
    fieldsRoot: {
        height: (props) => 'calc(100vh - 288px)'
    },
    title: {
        display: 'flex',
        justifyContent: 'space-between',
        margin: theme.spacing(1)
    },
    buttonWrapper: {
        textAlign: 'center'
    },
    button: {
        textTransform: 'none',
        padding: 0,
        '&:hover': {
            backgroundColor: 'rgba(0, 0, 0, 0)'
        },
        color: theme.palette.secondary
    }
}));
export const InquiryAdvancedSearch = (props) => {
    const { entityList, onSubmit, currentNodeCatalogReturnObject, catalogObjects, entityValue, setEntityValue, changeSideBarView, tree, executeQueryWithParameters } = props;
    const classes = useStyles(props);
    const [initialSelectedSearchOperators, setInitialSelectedSearchOperators] = useState(null);
    const [selectedSearchOperators, setSelectedSearchOperators] = useState(null);
    const [form, setForm] = useState(null);
    const entityTree = useMemo(() => {
        var _a, _b;
        if (!entityValue || !tree) {
            return null;
        }
        const matchingEntityTree = tree.treeStructure.find((node) => node.properties.catalogReturnObject === entityValue.value);
        let nodeTree = tree;
        if ((_a = matchingEntityTree === null || matchingEntityTree === void 0 ? void 0 : matchingEntityTree.properties) === null || _a === void 0 ? void 0 : _a.associatedInquiryTree) {
            nodeTree = (_b = matchingEntityTree === null || matchingEntityTree === void 0 ? void 0 : matchingEntityTree.properties) === null || _b === void 0 ? void 0 : _b.associatedInquiryTree;
        }
        return nodeTree;
    }, [tree, entityValue]);
    const catalogProperties = useMemo(() => {
        if (!entityValue || !catalogObjects) {
            return [];
        }
        const foundCatalogObject = catalogObjects.find((catalog) => catalog.catalogObjectName === entityValue.value);
        return (foundCatalogObject === null || foundCatalogObject === void 0 ? void 0 : foundCatalogObject.properties) || [];
    }, [catalogObjects, entityValue]);
    const advancedSearchFields = useMemo(() => {
        var _a, _b;
        if (!entityTree) {
            return null;
        }
        const parentNode = entityTree.treeStructure.find((node) => !node.parentId);
        const advancedSearchConfiguration = (_b = (_a = parentNode === null || parentNode === void 0 ? void 0 : parentNode.properties) === null || _a === void 0 ? void 0 : _a.searchConfiguration) === null || _b === void 0 ? void 0 : _b.filter((config) => config.advancedSearch);
        advancedSearchConfiguration === null || advancedSearchConfiguration === void 0 ? void 0 : advancedSearchConfiguration.forEach((config) => (config.advancedSearch = Number.parseFloat(config.advancedSearch)));
        const orderedSearchConfiguration = orderBy(advancedSearchConfiguration, ['advancedSearch'], ['asc']);
        const groupedAndOrderdFields = {};
        orderedSearchConfiguration.forEach((config) => {
            const wholeInt = Math.floor(config.advancedSearch);
            if (!groupedAndOrderdFields[wholeInt]) {
                groupedAndOrderdFields[wholeInt] = [config];
            }
            else {
                groupedAndOrderdFields[wholeInt].push(config);
            }
        });
        return groupedAndOrderdFields;
    }, [entityTree]);
    const asCatalogLookupPropertyNames = useMemo(() => {
        var _a, _b;
        if (!entityTree) {
            return [];
        }
        const parentNode = entityTree.treeStructure.find((node) => !node.parentId);
        const advancedSearchPropertyName = (_b = (_a = parentNode === null || parentNode === void 0 ? void 0 : parentNode.properties) === null || _a === void 0 ? void 0 : _a.searchConfiguration) === null || _b === void 0 ? void 0 : _b.filter((config) => config.advancedSearch).map((asConfig) => asConfig.name);
        const filteredProperties = catalogProperties.filter((property) => advancedSearchPropertyName === null || advancedSearchPropertyName === void 0 ? void 0 : advancedSearchPropertyName.includes(property.name));
        const lookupPropertyNames = [];
        filteredProperties.forEach((property) => {
            var _a, _b;
            if (((_a = property === null || property === void 0 ? void 0 : property.extendedProperties) === null || _a === void 0 ? void 0 : _a.useLookup) !== LookupTypeEnums.No_Lookup ||
                !((_b = property === null || property === void 0 ? void 0 : property.extendedProperties) === null || _b === void 0 ? void 0 : _b.useLookup)) {
                lookupPropertyNames.push(property.name);
            }
        });
        return lookupPropertyNames;
    }, [catalogProperties, entityTree]);
    const handleEntityChange = (value) => {
        setEntityValue(value);
    };
    const handleOnSubmit = useCallback((values) => {
        if (onSubmit) {
            onSubmit(values, selectedSearchOperators, entityValue === null || entityValue === void 0 ? void 0 : entityValue.value, asCatalogLookupPropertyNames);
        }
    }, [
        onSubmit,
        selectedSearchOperators,
        entityValue,
        asCatalogLookupPropertyNames
    ]);
    const handleClearFilter = useCallback(() => {
        if (form) {
            form.reset();
        }
        setSelectedSearchOperators(initialSelectedSearchOperators);
    }, [initialSelectedSearchOperators, form]);
    useEffect(() => {
        if (entityList === null || entityList === void 0 ? void 0 : entityList.length) {
            const foundEntity = entityList.find((entity) => entity.value === currentNodeCatalogReturnObject);
            if (foundEntity) {
                setEntityValue(foundEntity);
            }
        }
    }, [entityList, currentNodeCatalogReturnObject, setEntityValue]);
    useEffect(() => {
        if (advancedSearchFields) {
            const mergedFields = [].concat.apply([], Object.values(advancedSearchFields));
            const initialSearchOperators = mergedFields.reduce((operators, field) => {
                if (field.advancedSearchOperator) {
                    const foundOperator = SearchOperators.find((op) => op.value === field.advancedSearchOperator);
                    operators[field.name] = foundOperator !== null && foundOperator !== void 0 ? foundOperator : SearchOperators[0];
                }
                else {
                    operators[field.name] = SearchOperators[0];
                }
                return operators;
            }, {});
            setInitialSelectedSearchOperators(initialSearchOperators);
            setSelectedSearchOperators(initialSearchOperators);
        }
    }, [advancedSearchFields]);
    return (React.createElement("div", { className: classes.root }, React.createElement("div", null, React.createElement(Divider, null)), React.createElement("div", { className: classes.title }, React.createElement(Typography, { variant: "subtitle1" }, "Advanced Search"), React.createElement(FluentIconButton, { id: "udpRecord-InquiryAdvancedSearch-ClearIcon", udprecordid: "udpRecord-InquiryAdvancedSearch-ClearIcon", icon: ClearIcon, onClick: () => changeSideBarView(0) })), React.createElement("div", { className: classes.entitySelect }, React.createElement(FluentTextFieldAutoComplete, { id: "udpRecord-InquiryAdvancedSearch-TextField", udprecordid: "udpRecord-InquiryAdvancedSearch-TextField", label: "Entity", variant: "outlined", margin: "normal", size: "small", fullWidth: true, options: entityList, optionKey: "label", value: entityValue, onChange: handleEntityChange })), React.createElement(Form, { onSubmit: handleOnSubmit }, React.createElement(InquiryAdvancedSearchForm, { advancedSearchFields: advancedSearchFields, selectedSearchOperators: selectedSearchOperators, setSelectedSearchOperators: setSelectedSearchOperators, catalogProperties: catalogProperties, entityType: getSanitizedName(entityValue === null || entityValue === void 0 ? void 0 : entityValue.value), lookupPropertyNames: asCatalogLookupPropertyNames, classes: { root: classes.fieldsRoot }, executeQueryWithParameters: executeQueryWithParameters, setForm: setForm }), React.createElement("div", { className: classes.submitWrapper }, React.createElement("div", { className: classes.buttonWrapper }, React.createElement(FluentButton, { id: "udpRecord-InquiryAdvancedSearch-ClearFilter", udprecordid: "udpRecord-InquiryAdvancedSearch-ClearFilter", onClick: handleClearFilter, className: classes.button }, React.createElement(Typography, { variant: "subtitle1" }, "Clear Filter")), React.createElement(FormButtons, null, React.createElement(SubmitButton, { id: "udpRecord-InquiryAdvancedSearch-Search", udprecordid: "udpRecord-InquiryAdvancedSearch-Search", variant: "contained", color: "primary", disablePristine: false, disabled: !entityValue, fullWidth: true, style: { marginRight: 8, marginLeft: 8 } }, "Searc")))))));
};
//# sourceMappingURL=InquiryAdvancedSearch.js.map