import * as React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import DropdownButton from '../../../../components/DropdownButton';
import EmptyContent from '../../../../components/EmptyContent';
import { Icon } from '../../../../components/icons';
import { AdaptableObjectList } from '../../AdaptableObjectList';
import { ButtonNew } from '../../Buttons/ButtonNew';
import { PopupPanel } from './PopupPanel';
import { Flex } from 'rebass';
import { CheckBox } from '../../../../components/CheckBox';
import { LayoutShowNotAssociatedObjects } from '../../../../Redux/ActionsReducers/InternalRedux';
import SimpleButton from '../../../../components/SimpleButton';
import { useAdaptable } from '../../../AdaptableContext';
import { useEffect } from 'react';
import { useRerender } from '../../../../components/utils/useRerender';
export const AdaptablePopupModuleView = (props) => {
    /**
     * This triggers a render for each state change.
     * NOT sure this is still needed... It is here for historical reasons.
     */
    const adaptable = useAdaptable();
    const rerender = useRerender();
    useEffect(() => {
        return adaptable.api.eventApi.on('AdaptableStateChanged', rerender);
    }, [adaptable]);
    const [abObjectType, setAbObjectType] = React.useState(null);
    const moduleInfo = props.module.moduleInfo;
    const items = props.module?.toViewAll();
    const moduleViewProperties = props.module?.getViewProperties?.() ?? {};
    const EditWizard = moduleViewProperties?.getEditWizard?.();
    const [isWizardOpen, setIsWizardOpen] = React.useState(() => {
        return (props.popupParams?.action === 'New' ||
            props.popupParams?.action === 'Edit' ||
            props.popupParams?.action === 'Clone');
    });
    const handleOpenEditPopup = React.useCallback(() => {
        if (EditWizard) {
            setIsWizardOpen(true);
        }
        if (moduleViewProperties.onOpenEditPopup) {
            moduleViewProperties.onOpenEditPopup();
        }
    }, []);
    React.useEffect(() => {
        moduleViewProperties?.onMount?.();
    }, []);
    React.useEffect(() => {
        if (props.popupParams?.action === 'New' ||
            props.popupParams?.action === 'Edit' ||
            props.popupParams?.action === 'Clone') {
            handleOpenEditPopup();
        }
    }, [props.popupParams?.action]);
    const emptyView = moduleViewProperties.emptyView;
    let emptyContent = null;
    if (typeof emptyView === 'function') {
        emptyContent = React.createElement(emptyView, { module: props.module });
    }
    else if (typeof emptyView === 'string') {
        emptyContent = emptyView;
    }
    const toolTipText = moduleViewProperties.newTooltipText ?? `Create ${moduleInfo.FriendlyName}`;
    // Some modules do not have new button
    // e.g. filter
    let newButton = null;
    if (moduleViewProperties?.abObjectTypes?.length) {
        const items = moduleViewProperties?.abObjectTypes.map((abObjectType) => {
            return {
                disabled: abObjectType?.accessLevel === 'ReadOnly',
                onClick: () => {
                    setAbObjectType(abObjectType);
                    handleOpenEditPopup();
                },
                label: abObjectType.label ?? abObjectType.name,
            };
        });
        newButton = (React.createElement(DropdownButton, { tone: "accent", variant: "raised", columns: ['label'], items: items, tooltip: toolTipText },
            React.createElement(Icon, { name: "plus" }),
            " New"));
    }
    else if (!moduleViewProperties.hideNewButton &&
        (EditWizard || moduleViewProperties.onOpenEditPopup)) {
        newButton = (React.createElement(ButtonNew, { onClick: () => handleOpenEditPopup(), tooltip: toolTipText, accessLevel: props.accessLevel }));
    }
    let suspendButton = null;
    const editableObjects = items.filter((item) => !item.abObject.IsReadOnly);
    if (editableObjects.length &&
        moduleViewProperties?.getSuspendAllAction &&
        moduleViewProperties?.getUnSuspendAllAction) {
        const isAtLeastOneAbObjectActive = editableObjects.some((item) => {
            return !item.abObject?.IsSuspended;
        });
        const handleSuspendUnsuspendAll = () => {
            if (isAtLeastOneAbObjectActive) {
                const suspendAllAction = moduleViewProperties.getSuspendAllAction();
                dispatch(suspendAllAction);
            }
            else {
                const unsuspendAllAction = moduleViewProperties.getUnSuspendAllAction();
                dispatch(unsuspendAllAction);
            }
        };
        suspendButton = (React.createElement(SimpleButton, { mr: 2, onMouseDown: () => handleSuspendUnsuspendAll(), tone: isAtLeastOneAbObjectActive ? 'neutral' : 'success', variant: "raised", icon: isAtLeastOneAbObjectActive ? 'pause' : 'resume', accessLevel: props.accessLevel }, isAtLeastOneAbObjectActive ? 'Suspend All' : 'Unsuspend All'));
    }
    const handleWizardClose = () => {
        setAbObjectType(null);
        setIsWizardOpen(false);
        if (['Toolbar', 'ContextMenu', 'ColumnMenu'].includes(props?.popupParams?.source)) {
            props.onClosePopup();
        }
    };
    const adaptableModule = props.api.internalApi
        .getModuleService()
        .getModuleById(props.module.moduleInfo.ModuleName);
    const dispatch = useDispatch();
    const showLayoutNotAssociatedObjects = useSelector((state) => state.Internal.Layout.ShowLayoutNotAssociatedObjects);
    const toggleButtonShowLayoutAssociatedObjects = () => {
        if (!adaptableModule?.canBeAssociatedWithLayouts()) {
            return;
        }
        if (!props.api.layoutApi.internalApi.hasLayoutSpecificObjects()) {
            return;
        }
        return (React.createElement(Flex, { justifyContent: "flex-start" },
            React.createElement(CheckBox, { padding: 0, margin: 0, checked: showLayoutNotAssociatedObjects, onChange: (checked) => dispatch(LayoutShowNotAssociatedObjects(checked)) },
                "Show ",
                moduleInfo.FriendlyName,
                "s not available in current Layout")));
    };
    return (React.createElement(PopupPanel, { glyphicon: moduleInfo.Glyph, infoLink: moduleInfo.HelpPage, headerText: moduleInfo.FriendlyName, button: React.createElement(React.Fragment, null,
            suspendButton,
            " ",
            newButton), infoLinkDisabled: !props.api.internalApi.isDocumentationLinksDisplayed() },
        moduleViewProperties.HeaderComponent && React.createElement(moduleViewProperties.HeaderComponent, null),
        toggleButtonShowLayoutAssociatedObjects(),
        items?.length ? (React.createElement(AdaptableObjectList, { module: props.module, items: items })) : (React.createElement(EmptyContent, null, emptyContent ?? `Click 'New' to create a new ${moduleInfo.FriendlyName}`)),
        isWizardOpen && EditWizard && (React.createElement(EditWizard, { abObjectType: abObjectType, moduleInfo: moduleInfo, data: null, popupParams: props.popupParams, configEntities: null, onCloseWizard: handleWizardClose, onFinishWizard: handleWizardClose }))));
};
