import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ClientSideUdpGrid } from '../../../UI/templates/newGrid';
import { getSearchObject } from '../../../utilities/search/SearchUtilities';
import { executeQueryAdHoc, getBaseMethod } from '../../utilities/methodUtils';
import { UdpEnums } from '../../../enums/unitySystemEnums';
import { useActionState } from '../../../hooks/useActions';
import { useHandleAxiosSnackbar } from '../../../utilities/apiHelpers';
import { useTranslation } from 'react-i18next';
import { NotesScreen } from '../../../notes/NotesScreen';
import { SideSheet } from '../../../UI/surfaces/SideSheet';
import { useActions } from '../../../hooks/useActions';
import { SplitScreenTypeEnums } from '../../../enums/unitySystemEnums';
import { useUser } from '../../../utilities/auth/useUser';
const GRID_ID = '52904970-8669-418e-b762-febb9ab38bad';
const UdpNotesPage = (props) => {
    const { params } = props;
    const { nodeObj, manytoManyNodeObjKey } = params;
    const [notes, setNotes] = useState([]);
    const [typeOptions, setTypeOptions] = useState([]);
    const [loading, setLoading] = useState(false);
    const [sheetOpen, setSheetOpen] = useState(false);
    const [noteId, setNoteId] = useState('');
    const { openSplitScreen } = useActions();
    const actionState = useActionState();
    const { catalogPromotedEntities } = actionState;
    const { handleErrorSnackbar } = useHandleAxiosSnackbar();
    const { t } = useTranslation();
    const formRef = useRef(null);
    const gridApiRef = useRef(null);
    const user = useUser();
    const noteFiledForSearchApiMethod = useMemo(() => {
        return getBaseMethod(UdpEnums.Udp_Note_Filed_For, 'unityBaseSearchMethod', catalogPromotedEntities);
    }, [catalogPromotedEntities]);
    const noteTypeGetAllApiMethod = useMemo(() => {
        return getBaseMethod(UdpEnums.Udp_Note_Type, 'unityBaseGetAllMethod', catalogPromotedEntities);
    }, [catalogPromotedEntities]);
    const getNotes = useCallback(async () => {
        var _a;
        if (!nodeObj) {
            return [];
        }
        let notesList = [];
        setLoading(true);
        const filterElements = [
            {
                searchField: 'entityBusinessKey',
                searchValue: manytoManyNodeObjKey
                    ? (_a = nodeObj[manytoManyNodeObjKey]) === null || _a === void 0 ? void 0 : _a.businessObjectKey
                    : nodeObj === null || nodeObj === void 0 ? void 0 : nodeObj.businessObjectKey,
                searchOperator: '='
            }
        ];
        const searchObject = getSearchObject(filterElements, 1, 200, true);
        const data = { data: searchObject };
        if (noteFiledForSearchApiMethod) {
            const response = await executeQueryAdHoc(data, noteFiledForSearchApiMethod.apiMethodId);
            if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
                const pageList = response.data.pageList;
                if (pageList === null || pageList === void 0 ? void 0 : pageList.length) {
                    notesList = pageList.map((item) => item.note);
                }
            }
            else {
                handleErrorSnackbar(null, t('Could not retrieve notes'));
            }
        }
        else {
            handleErrorSnackbar(null, t('Search NoteFiledFor Method Not Promoted'));
        }
        setLoading(false);
        setNotes(notesList);
    }, [
        noteFiledForSearchApiMethod,
        handleErrorSnackbar,
        nodeObj,
        manytoManyNodeObjKey,
        t,
        user
    ]);
    const openSheet = useCallback((value) => {
        setNoteId((value === null || value === void 0 ? void 0 : value.id) || '');
        setSheetOpen(true);
    }, []);
    const closeSheet = useCallback(() => {
        setNoteId('');
        setSheetOpen(false);
    }, []);
    const handleEditPage = useCallback((value) => {
        openSplitScreen({
            open: true,
            action: null,
            type: SplitScreenTypeEnums.Notes,
            params: { id: (value === null || value === void 0 ? void 0 : value.id) || '', reloadNotes: getNotes }
        });
    }, [openSplitScreen, getNotes]);
    const getType = useCallback((params) => {
        const type = typeOptions.find((t) => t.code === params.data.typeCode);
        return (type === null || type === void 0 ? void 0 : type.name) || '';
    }, [typeOptions]);
    const actionList = useMemo(() => [
        {
            id: 1, // Must be unique
            title: t('Note'),
            iconName: 'view',
            handleOnClick: (e, params) => openSheet(params === null || params === void 0 ? void 0 : params.data),
            disabled: false
        },
        {
            id: 2, // Must be unique
            title: t('Edit'),
            iconName: 'edit',
            handleOnClick: (e, params) => handleEditPage(params === null || params === void 0 ? void 0 : params.data),
            disabled: false
        }
    ], [t, openSheet, handleEditPage]);
    const columnDefs = [
        {
            headerName: 'Date',
            field: 'createdOn',
            resizable: true,
            sortable: true
        },
        {
            headerName: 'Subject',
            field: 'subject',
            resizable: true,
            sortable: true
        },
        {
            headerName: 'Note',
            field: 'content',
            resizable: true,
            sortable: true,
            valueGetter: (params) => {
                var _a;
                return ((_a = params.data.content) === null || _a === void 0 ? void 0 : _a.replace(/(<([^>]+)>)/gi, '')) || '';
            }
        },
        {
            headerName: 'Type',
            field: 'typeCode',
            resizable: true,
            sortable: true,
            valueGetter: getType
        },
        {
            headerName: 'Created By',
            field: 'userDisplayName',
            resizable: true,
            sortable: true
        },
        {
            headerName: '',
            cellRenderer: 'actionsRenderer',
            cellRendererParams: {
                actionList
            },
            pinned: 'right',
            suppressMenu: true,
            sortable: false
        }
    ];
    const gridFunctions = [
        { name: 'quickFilter' },
        { name: 'agGridExport' },
        { name: 'agGridSizeColumnsToFit' },
        { name: 'agGridAutoSizeColumns' },
        { name: 'agGridResetColumns' },
        { name: 'agGridHideShowColumns' },
        { name: 'openSavedViews' }
    ];
    const gridOptions = useMemo(() => {
        return {
            pagination: true
        };
    }, []);
    const handleGridApiCallback = (api) => {
        gridApiRef.current = api;
    };
    // no dependencies in the array because we only want getNotes to run once
    useEffect(() => {
        getNotes();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    useEffect(() => {
        const getTypeOptions = async () => {
            let options = [];
            if (noteTypeGetAllApiMethod) {
                const typesResponse = await executeQueryAdHoc({ data: {} }, noteTypeGetAllApiMethod.apiMethodId);
                if ((typesResponse === null || typesResponse === void 0 ? void 0 : typesResponse.status) === 200) {
                    options = typesResponse.data;
                }
            }
            setTypeOptions(options);
        };
        getTypeOptions();
    }, [noteTypeGetAllApiMethod]);
    return (React.createElement(React.Fragment, null, React.createElement(SideSheet, { open: sheetOpen, onClose: closeSheet, title: t('Note'), width: 600 }, React.createElement(NotesScreen, { viewOnly: true, id: noteId, shortcutContentFinderEnabled: false, formRef: formRef })), React.createElement(ClientSideUdpGrid, { gridId: GRID_ID, rowData: notes, loading: loading, columnDefs: columnDefs, gridHeaderConfig: { title: t('Notes') }, gridFunctions: gridFunctions, gridOptions: gridOptions, gridApiCallback: handleGridApiCallback })));
};
export default UdpNotesPage;
//# sourceMappingURL=UdpNotesPage.js.map