import * as React from 'react';
import { Box, Flex, Text } from 'rebass';
import { CheckBox } from '../../../../components/CheckBox';
import DropdownButton from '../../../../components/DropdownButton';
import FormLayout, { FormRow } from '../../../../components/FormLayout';
import { Tabs } from '../../../../components/Tabs';
import { Tag } from '../../../../components/Tag';
import { useAdaptable } from '../../../AdaptableContext';
import { ValueSelector } from '../../../Components/ValueSelector';
import { useOnePageAdaptableWizardContext } from '../../../Wizard/OnePageAdaptableWizard';
import { columnFilter } from './Utilities';
import ArrayExtensions from '../../../../Utilities/Extensions/ArrayExtensions';
const PivotColumnRow = (props) => {
    const adaptable = useAdaptable();
    const aggValue = (props.layout.PivotAggregationColumns || []).find((x) => x.ColumnId === props.column.columnId)?.AggFunc;
    const adaptableAggFunctions = [];
    if (props.column.dataType === 'number') {
        adaptableAggFunctions.push(WEIGHTED_AVERAGE_AGG_FN_NAME);
    }
    const aggOptions = [...props.column.availableAggregationFunctions, ...adaptableAggFunctions].map((fnName) => {
        return {
            label: fnName,
            onClick: () => {
                let aggCols = props.layout.PivotAggregationColumns;
                if (!aggCols) {
                    return;
                }
                if (fnName === WEIGHTED_AVERAGE_AGG_FN_NAME) {
                    aggCols = aggCols.map((x) => {
                        if (x.ColumnId === props.column.columnId) {
                            return {
                                ...x,
                                type: 'weightedAverage',
                                weightedColumnId: null,
                            };
                        }
                        return x;
                    });
                }
                else {
                    aggCols = aggCols.map((x) => {
                        if (x.ColumnId === props.column.columnId) {
                            return {
                                ...x,
                                AggFunc: fnName,
                            };
                        }
                        return x;
                    });
                }
                props.onChangeAggFunction(aggCols);
            },
        };
    });
    const numericColumnsOptions = props.numberColumns
        .filter((col) => col.columnId !== props.column.columnId)
        .map((col) => {
        return {
            label: col.friendlyName,
            onClick: () => {
                let aggCols = props.layout.PivotAggregationColumns;
                if (!aggCols) {
                    return;
                }
                aggCols = aggCols.map((x) => {
                    if (x.ColumnId === props.column.columnId) {
                        return {
                            ...x,
                            type: 'weightedAverage',
                            weightedColumnId: col.columnId,
                        };
                    }
                    return x;
                });
                props.onChangeAggFunction(aggCols);
            },
        };
    });
    const currentAggFnName = props.aggregationColumnsMap[props.column.columnId];
    let weightName = null;
    if (typeof aggValue === 'object' && aggValue.type === 'weightedAverage') {
        weightName = aggValue.weightedColumnId
            ? adaptable.api.columnApi.getFriendlyNameForColumnId(aggValue.weightedColumnId)
            : 'Select Weight';
    }
    return (React.createElement(Flex, { alignItems: "center" },
        props.column.friendlyName,
        aggValue && (React.createElement(DropdownButton, { columns: ['label'], items: aggOptions, ml: 2 }, currentAggFnName)),
        currentAggFnName === WEIGHTED_AVERAGE_AGG_FN_NAME && (React.createElement(Flex, { backgroundColor: "primary", ml: 3, alignItems: "center" },
            React.createElement(Text, null, "Weight"),
            ' ',
            React.createElement(DropdownButton, { columns: ['label'], items: numericColumnsOptions, ml: 2 }, weightName)))));
};
const WEIGHTED_AVERAGE_AGG_FN_NAME = 'weightedAvg';
export const isAggregationsSectionValid = (data) => {
    const weightedAvg = data.TableAggregationColumns
        ? (data.TableAggregationColumns || [])
            .map((agg) => agg.AggFunc)
            .find((agg) => typeof agg === 'object' && agg.type === 'weightedAverage')
        : null;
    if (weightedAvg && !weightedAvg.weightedColumnId) {
        return 'The Weighted Average Aggregation requires a Weighted Column';
    }
    return true;
};
export const PivotAggregationsSectionSummary = () => {
    const adaptable = useAdaptable();
    const { data: layout } = useOnePageAdaptableWizardContext();
    const pivotAggregationColumns = layout.PivotAggregationColumns || [];
    let content = null;
    if (pivotAggregationColumns.length) {
        content = (React.createElement(FormLayout, null, pivotAggregationColumns.map(({ ColumnId: colId, AggFunc: aggFunc }) => (React.createElement(FormRow, { key: colId, label: adaptable.api.columnApi.getFriendlyNameForColumnId(colId) },
            React.createElement(Tag, null, typeof aggFunc === 'object' ? aggFunc.type : aggFunc))))));
    }
    else {
        content = React.createElement(Tag, null, "No Pivot Column Aggregations");
    }
    return React.createElement(Box, null, content);
};
export const PivotAggregationsSection = (props) => {
    const adaptable = useAdaptable();
    const { data: layout } = useOnePageAdaptableWizardContext();
    const allAggregableColumns = adaptable.api.columnApi.getAggregatableColumns();
    const allColumns = adaptable.api.columnApi.getUIAvailableColumns();
    const numberColumns = adaptable.api.columnApi.getNumericColumns();
    const sortedAggregableColumns = React.useMemo(() => {
        return ArrayExtensions.sortArrayWithOrder(allAggregableColumns.map((col) => col.columnId), (layout.PivotAggregationColumns ?? []).map((col) => col.ColumnId), { sortUnorderedItems: false }).map((colId) => adaptable.api.columnApi.getColumnWithColumnId(colId));
    }, [layout, allAggregableColumns]);
    globalThis.layout = layout;
    const handleColumnsSelectionChange = React.useCallback((columnIds) => {
        const currentAggColumns = layout.PivotAggregationColumns ?? [];
        const PivotAggregationColumns = columnIds.map((colId) => {
            return {
                ColumnId: colId,
                AggFunc: currentAggColumns.find((x) => x.ColumnId === colId)?.AggFunc ??
                    adaptable.api.columnApi.getDefaultAggFunc(colId),
            };
        });
        props.onChange({
            ...layout,
            PivotAggregationColumns,
        });
    }, [layout]);
    const handleAggregationChange = React.useCallback((PivotAggregationColumns) => {
        props.onChange({
            ...layout,
            PivotAggregationColumns,
        });
    }, [layout]);
    const aggregationColumnsMap = React.useMemo(() => {
        const allColumnsMap = allColumns.reduce((acc, col) => {
            acc[col.columnId] = col;
            return acc;
        }, {});
        return (layout.PivotAggregationColumns || []).reduce((acc, { ColumnId: colId, AggFunc: aggFunc }) => {
            let fn = aggFunc;
            let fnName = '';
            if (typeof fn === 'boolean') {
                fnName = allColumnsMap[colId].aggregationFunction;
            }
            if (typeof fn === 'object' && fn.type === 'weightedAverage') {
                fnName = WEIGHTED_AVERAGE_AGG_FN_NAME;
            }
            else if (typeof fn === 'string') {
                fnName = fn;
            }
            acc[colId] = fnName;
            return acc;
        }, {});
    }, [layout]);
    const handleSuppressAggFuncInHeader = (checked) => {
        props.onChange({
            ...layout,
            SuppressAggFuncInHeader: checked,
        });
    };
    return (React.createElement(Tabs, { style: { height: '100%' } },
        React.createElement(Tabs.Tab, null, "Column Aggregations"),
        React.createElement(Tabs.Content, null,
            React.createElement(Flex, null,
                React.createElement(FormLayout, null,
                    React.createElement(CheckBox, { checked: layout.SuppressAggFuncInHeader, onChange: handleSuppressAggFuncInHeader }, "Suppress Aggregation Function Text in Column Header"))),
            React.createElement(ValueSelector, { showFilterInput: true, showSelectedOnlyPosition: "top", filter: columnFilter, toIdentifier: (option) => `${option.columnId}`, toLabel: (option) => option.friendlyName ?? option.columnId, toListLabel: (column) => (React.createElement(PivotColumnRow, { onChangeAggFunction: handleAggregationChange, layout: layout, column: column, aggregationColumnsMap: aggregationColumnsMap, numberColumns: numberColumns })), options: sortedAggregableColumns, value: (layout.PivotAggregationColumns || []).map((col) => col.ColumnId), allowReorder: true, xSelectedLabel: () => {
                    return `Active aggregations:`;
                }, onChange: handleColumnsSelectionChange }))));
};
