import * as React from 'react';
import * as LayoutRedux from '../../../Redux/ActionsReducers/LayoutRedux';
import { OnePageAdaptableWizard, OnePageWizardSummary } from '../../Wizard/OnePageAdaptableWizard';
import ObjectFactory from '../../../Utilities/ObjectFactory';
import { cloneObject } from '../../../Utilities/Helpers/Helper';
import { SettingsSection, SettingsSectionSummary } from './sections/SettingsSection';
import { Box } from 'rebass';
import { useAdaptable } from '../../AdaptableContext';
import { useDispatch } from 'react-redux';
import { ColumnsSection, ColumnsSectionSummary } from './sections/ColumnsSection';
import { PivotColumnsSection, PivotColumnsSectionSummary } from './sections/PivotColumnsSection';
import { RowGroupingSection, RowGroupingSectionSummary } from './sections/RowGroupingSection';
import { AggregationsSection, AggregationsSectionSummary, isAggregationsSectionValid, } from './sections/AggregationsSection';
import { SortSection, SortSectionSummary } from './sections/SortSection';
import { FilterSection, FilterSectionSummary, isColumnFiltersValid, } from './sections/FilterSection';
import { GridFilterSection, GridFilterSectionSummary, isGridFiltersValid, } from './sections/GridFilterSection';
import { areSummaryRowsValid, RowSummarySection, RowSummarySectionSummary, } from './sections/RowSummarySection';
import { WEIGHTED_AVERAGE_AGGREGATED_FUNCTION } from '../../../AdaptableState/Common/RowSummary';
import { isPivotLayout } from '../../../Utilities/isPivotLayout';
import { PivotRowGroupingSection, PivotRowGroupingSectionSummary, } from './sections/PivotRowGroupingSection';
import { isPivotAggregationsSectionValid, PivotAggregationsSection, PivotAggregationsSectionSummary, } from './sections/PivotAggregationsSection';
export const LayoutWizard = (props) => {
    const dispatch = useDispatch();
    const adaptable = useAdaptable();
    const allLayouts = adaptable.api.layoutApi.getLayouts();
    const initialLayout = props.data ?? props.popupParams?.value;
    const [layout, setLayout] = React.useState(() => {
        let preparedLayout = null;
        if (initialLayout) {
            preparedLayout = cloneObject(initialLayout);
            if (props?.popupParams?.action === 'Clone') {
                preparedLayout.Name = '';
                delete preparedLayout.Uuid;
            }
        }
        else {
            const shouldCreatePivot = props.popupParams?.config?.layoutType === 'pivot' ||
                props.abObjectType?.name?.toLowerCase().includes('pivot') ||
                false;
            preparedLayout = shouldCreatePivot
                ? ObjectFactory.CreateEmptyPivotLayout({ Name: '' })
                : ObjectFactory.CreateEmptyLayout({ Name: '' });
        }
        if (preparedLayout.SuppressAggFuncInHeader === undefined) {
            preparedLayout.SuppressAggFuncInHeader =
                !!adaptable.api.agGridApi.getGridOption('suppressAggFuncInHeader');
        }
        return preparedLayout;
    });
    const handleFinish = () => {
        let action = props?.popupParams?.action;
        if (!action) {
            action = initialLayout ? 'Edit' : 'New';
        }
        switch (action) {
            case 'Edit':
                const currentLayout = adaptable.api.layoutApi.getCurrentLayout();
                dispatch(LayoutRedux.LayoutSave(layout));
                if (currentLayout.Uuid === layout.Uuid) {
                    dispatch(LayoutRedux.LayoutSelect(layout.Name));
                }
                break;
            case 'Clone':
                const clonedLayout = { ...layout };
                delete clonedLayout.Uuid;
                dispatch(LayoutRedux.LayoutAdd(clonedLayout));
                dispatch(LayoutRedux.LayoutSelect(clonedLayout.Name));
                break;
            case 'New':
                dispatch(LayoutRedux.LayoutAdd(layout));
                dispatch(LayoutRedux.LayoutSelect(layout.Name));
        }
        props.onFinishWizard(layout);
    };
    const layoutSupportedFeatures = adaptable.api.layoutApi.internalApi.getLayoutSupportedFeatures();
    return isPivotLayout(layout) ? (React.createElement(OnePageAdaptableWizard, { titleContainerStyle: { width: 180 }, defaultCurrentSectionName: props.defaultCurrentSectionName, moduleInfo: props.moduleInfo, data: layout, onHide: props.onCloseWizard, onFinish: handleFinish, sections: [
            {
                title: 'Settings',
                details: 'Configure Pivot Layout',
                isValid: () => {
                    if (!layout.Name) {
                        return 'Pivot Layout Name cannot be blank';
                    }
                    if (allLayouts.some((layoutItem) => layoutItem.Name === layout.Name && layoutItem.Uuid !== layout.Uuid)) {
                        return 'A Pivot Layout already exists with that name';
                    }
                    return true;
                },
                renderSummary: () => React.createElement(SettingsSectionSummary, null),
                render: () => (React.createElement(Box, { padding: 2 },
                    React.createElement(SettingsSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            {
                title: 'Pivot Row Groups',
                isVisible: () => layoutSupportedFeatures.PivotColumns && layoutSupportedFeatures.RowGroupedColumns,
                details: 'Configure Pivot Row Grouping',
                renderSummary: () => React.createElement(PivotRowGroupingSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(PivotRowGroupingSection, { onChange: (newLayout) => {
                            setLayout(newLayout);
                        } }))),
            },
            {
                title: 'Pivot Columns',
                details: 'Select Pivot Columns',
                isVisible: () => layoutSupportedFeatures.PivotColumns,
                renderSummary: () => React.createElement(PivotColumnsSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(PivotColumnsSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            {
                title: 'Pivot Aggregations',
                isVisible: () => layoutSupportedFeatures.PivotAggregationColumns && layoutSupportedFeatures.PivotColumns,
                details: 'Select Pivot Column Aggregations',
                renderSummary: () => React.createElement(PivotAggregationsSectionSummary, null),
                isValid: (data) => isPivotAggregationsSectionValid(data),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(PivotAggregationsSection, { onChange: (layout) => {
                            let newLayout = cloneObject(layout);
                            setLayout(newLayout);
                        } }))),
            },
            {
                title: 'Sort',
                isVisible: () => layoutSupportedFeatures.ColumnSorts,
                renderSummary: () => React.createElement(SortSectionSummary, null),
                details: 'Configure Aggregated Column Sorts',
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(SortSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            {
                title: 'Column Filters',
                isVisible: () => layoutSupportedFeatures.ColumnFilters,
                isValid: (layout) => isColumnFiltersValid(layout),
                details: 'Set Aggregated Column Filters',
                renderSummary: () => React.createElement(FilterSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(FilterSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            {
                title: 'Grid Filter',
                isVisible: () => layoutSupportedFeatures.GridFilter,
                isValid: (layout) => isGridFiltersValid(layout, adaptable.api),
                details: 'Set Grid Filter',
                renderSummary: () => React.createElement(GridFilterSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(GridFilterSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            '-',
            {
                details: 'Review your Pivot Layout',
                render: () => (React.createElement(Box, { padding: 2 },
                    React.createElement(OnePageWizardSummary, null))),
                title: 'Summary',
            },
        ] })) : (React.createElement(OnePageAdaptableWizard, { titleContainerStyle: { width: 180 }, defaultCurrentSectionName: props.defaultCurrentSectionName, moduleInfo: props.moduleInfo, data: layout, onHide: props.onCloseWizard, onFinish: handleFinish, sections: [
            {
                title: 'Settings',
                details: 'Configure Table Layout',
                isValid: () => {
                    if (!layout.Name) {
                        return 'Layout Name cannot be blank';
                    }
                    if (allLayouts.some((layoutItem) => layoutItem.Name === layout.Name && layoutItem.Uuid !== layout.Uuid)) {
                        return 'A Layout already exists with that name';
                    }
                    return true;
                },
                renderSummary: () => React.createElement(SettingsSectionSummary, null),
                render: () => (React.createElement(Box, { padding: 2 },
                    React.createElement(SettingsSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            {
                title: 'Row Groups',
                isVisible: () => layoutSupportedFeatures.RowGroupedColumns,
                isValid: areSummaryRowsValid,
                details: 'Configure Row Grouping',
                renderSummary: () => React.createElement(RowGroupingSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(RowGroupingSection, { onChange: setLayout }))),
            },
            {
                title: 'Columns',
                details: 'Select Columns',
                isVisible: () => true,
                renderSummary: () => React.createElement(ColumnsSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(ColumnsSection, { onChange: setLayout }))),
            },
            {
                title: 'Aggregations',
                isVisible: () => layoutSupportedFeatures.TableAggregationColumns,
                details: 'Select Column Aggregations',
                renderSummary: () => React.createElement(AggregationsSectionSummary, null),
                isValid: (data) => isAggregationsSectionValid(data),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(AggregationsSection, { onChange: (layout) => {
                            let newLayout = cloneObject(layout);
                            // if we do not have an weighted avg col, we need to clear the row summary if one exists
                            if (newLayout.RowSummaries) {
                                const aggColsMap = (newLayout.TableAggregationColumns || []).reduce((acc, { ColumnId, AggFunc }) => {
                                    acc[ColumnId] = AggFunc;
                                    return acc;
                                }, {});
                                newLayout.RowSummaries = newLayout.RowSummaries.map((rowSummary) => {
                                    return {
                                        ...rowSummary,
                                        ColumnsMap: Object.entries(rowSummary.ColumnsMap).reduce((acc, [columnId, aggFunc]) => {
                                            if (
                                            // see if it is weighted avg
                                            aggFunc === WEIGHTED_AVERAGE_AGGREGATED_FUNCTION &&
                                                // see if we have a weight in the agg columns
                                                aggColsMap[columnId] &&
                                                (typeof aggColsMap[columnId] !== 'object' ||
                                                    aggColsMap[columnId].weightColumnId)) {
                                                // need to remove the row summary
                                                return acc;
                                            }
                                            acc[columnId] = aggFunc;
                                            return acc;
                                        }, {}),
                                    };
                                });
                            }
                            setLayout(newLayout);
                        } }))),
            },
            {
                title: 'Row Summaries',
                details: 'Configure Row Summaries',
                renderSummary: () => React.createElement(RowSummarySectionSummary, null),
                isVisible: () => layoutSupportedFeatures.RowSummaries,
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(RowSummarySection, { onChange: setLayout }))),
            },
            {
                title: 'Sort',
                isVisible: () => layoutSupportedFeatures.ColumnSorts,
                renderSummary: () => React.createElement(SortSectionSummary, null),
                details: 'Configure Column Sorts',
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(SortSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            {
                title: 'Column Filters',
                isVisible: () => layoutSupportedFeatures.ColumnFilters,
                isValid: (layout) => isColumnFiltersValid(layout),
                details: 'Set Column Filters',
                renderSummary: () => React.createElement(FilterSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(FilterSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            {
                title: 'Grid Filter',
                isVisible: () => layoutSupportedFeatures.GridFilter,
                isValid: (layout) => isGridFiltersValid(layout, adaptable.api),
                details: 'Set Grid Filter',
                renderSummary: () => React.createElement(GridFilterSectionSummary, null),
                render: () => (React.createElement(Box, { p: 2, style: { height: '100%' } },
                    React.createElement(GridFilterSection, { onChange: (newLayout) => setLayout(newLayout) }))),
            },
            '-',
            {
                details: 'Review your Table Layout',
                render: () => (React.createElement(Box, { padding: 2 },
                    React.createElement(OnePageWizardSummary, null))),
                title: 'Summary',
            },
        ] }));
};
