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 { RemindersScreen } from '../../../reminders/RemindersScreen';
import { SideSheet } from '../../../UI/surfaces/SideSheet';
import { useActions } from '../../../hooks/useActions';
import { SplitScreenTypeEnums } from '../../../enums/unitySystemEnums';
import { FILE_TO_TYPES } from '../../../constants/reminderConstants';
import { useUser } from '../../../utilities/auth/useUser';
const GRID_ID = 'aac12169-8f86-4a03-b68b-f6d87ac9a2df';
const UdpRemindersPage = (props) => {
    const { params } = props;
    const { nodeObj, manytoManyNodeObjKey } = params;
    const [reminders, setReminders] = useState([]);
    const [typeOptions, setTypeOptions] = useState([]);
    const [loading, setLoading] = useState(false);
    const [sheetOpen, setSheetOpen] = useState(false);
    const [reminderId, setReminderId] = 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 reminderFiledForSearchApiMethod = useMemo(() => {
        return getBaseMethod(UdpEnums.Udp_Reminder_Filed_For, 'unityBaseSearchMethod', catalogPromotedEntities);
    }, [catalogPromotedEntities]);
    const reminderTypeGetAllApiMethod = useMemo(() => {
        return getBaseMethod(UdpEnums.Udp_Reminder_Type, 'unityBaseGetAllMethod', catalogPromotedEntities);
    }, [catalogPromotedEntities]);
    const getReminders = useCallback(async () => {
        var _a;
        if (!nodeObj) {
            return [];
        }
        let remindersList = [];
        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 (reminderFiledForSearchApiMethod) {
            const response = await executeQueryAdHoc(data, reminderFiledForSearchApiMethod.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) {
                    remindersList = pageList.map((item) => (Object.assign(Object.assign({}, item.reminder), { filedToType: item.type })));
                }
            }
            else {
                handleErrorSnackbar(null, t('Could not retrieve reminders'));
            }
        }
        else {
            handleErrorSnackbar(null, t('Search ReminderFiledFor Method Not Promoted'));
        }
        setLoading(false);
        setReminders(remindersList);
    }, [
        reminderFiledForSearchApiMethod,
        handleErrorSnackbar,
        nodeObj,
        manytoManyNodeObjKey,
        t,
        user
    ]);
    const openSheet = useCallback((value) => {
        setReminderId((value === null || value === void 0 ? void 0 : value.id) || '');
        setSheetOpen(true);
    }, []);
    const closeSheet = useCallback(() => {
        setReminderId('');
        setSheetOpen(false);
    }, []);
    const handleEditPage = useCallback((value) => {
        openSplitScreen({
            open: true,
            action: null,
            type: SplitScreenTypeEnums.Reminders,
            params: { id: (value === null || value === void 0 ? void 0 : value.id) || '', reloadReminders: getReminders }
        });
    }, [openSplitScreen, getReminders]);
    const actionList = useMemo(() => [
        {
            id: 1, // Must be unique
            title: t('Reminder'),
            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 getFiledToType = (params) => {
        const filedToType = FILE_TO_TYPES.find((type) => type.value === params.data.filedToType);
        return (filedToType === null || filedToType === void 0 ? void 0 : filedToType.label) || '';
    };
    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 columnDefs = [
        {
            headerName: 'Date',
            field: 'createdOn',
            resizable: true,
            sortable: true
        },
        {
            headerName: 'Subject',
            field: 'subject',
            resizable: true,
            sortable: true
        },
        {
            headerName: 'Reminder',
            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: 'Reminder Date',
            field: 'reminderDate',
            resizable: true,
            sortable: true
        },
        {
            headerName: 'Type',
            field: 'typeCode',
            resizable: true,
            sortable: true,
            valueGetter: getType
        },
        {
            headerName: 'Filed To Type',
            field: 'filedToType',
            resizable: true,
            sortable: true,
            valueGetter: getFiledToType
        },
        {
            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 getReminders to run once
    useEffect(() => {
        getReminders();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    useEffect(() => {
        const getTypeOptions = async () => {
            let options = [];
            if (reminderTypeGetAllApiMethod) {
                const typesResponse = await executeQueryAdHoc({ data: {} }, reminderTypeGetAllApiMethod.apiMethodId);
                if ((typesResponse === null || typesResponse === void 0 ? void 0 : typesResponse.status) === 200) {
                    options = typesResponse.data;
                }
            }
            setTypeOptions(options);
        };
        getTypeOptions();
    }, [reminderTypeGetAllApiMethod]);
    return (React.createElement(React.Fragment, null, React.createElement(SideSheet, { open: sheetOpen, onClose: closeSheet, title: t('Reminder'), width: 600 }, React.createElement(RemindersScreen, { viewOnly: true, id: reminderId, shortcutContentFinderEnabled: false, formRef: formRef })), React.createElement(ClientSideUdpGrid, { gridId: GRID_ID, rowData: reminders, loading: loading, columnDefs: columnDefs, gridHeaderConfig: { title: t('Reminders') }, gridFunctions: gridFunctions, gridOptions: gridOptions, gridApiCallback: handleGridApiCallback })));
};
export default UdpRemindersPage;
//# sourceMappingURL=UdpRemindersPage.js.map