import * as React from 'react';
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 { getAggFuncName, WEIGHTED_AVERAGE_AGG_FN_NAME, } from '../../../../AdaptableState/Common/AggregationColumns';
import { useAdaptable } from '../../../AdaptableContext';
import { ValueSelector } from '../../../Components/ValueSelector';
import { useOnePageAdaptableWizardContext } from '../../../Wizard/OnePageAdaptableWizard';
import { columnFilter } from './Utilities';
import ArrayExtensions from '../../../../Utilities/Extensions/ArrayExtensions';
import StringExtensions from '../../../../Utilities/Extensions/StringExtensions';
import { Select } from '../../../../components/Select';
import { Box, Flex } from '../../../../components/Flex';
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;
                }
                const AggFuncValue = fnName === WEIGHTED_AVERAGE_AGG_FN_NAME
                    ? {
                        type: 'weightedAverage',
                        weightedColumnId: null,
                    }
                    : fnName;
                let found = false;
                aggCols = aggCols.map(({ ColumnId, AggFunc }) => {
                    if (ColumnId === props.column.columnId) {
                        found = true;
                        return {
                            ColumnId,
                            AggFunc: AggFuncValue,
                        };
                    }
                    return { ColumnId, AggFunc };
                });
                if (!found) {
                    aggCols.push({
                        ColumnId: props.column.columnId,
                        AggFunc: AggFuncValue,
                    });
                }
                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;
                }
                const AggFuncValue = {
                    type: 'weightedAverage',
                    weightedColumnId: col.columnId,
                };
                let found = false;
                aggCols = aggCols.map(({ ColumnId, AggFunc }) => {
                    if (ColumnId === props.column.columnId) {
                        found = true;
                        return {
                            ColumnId,
                            AggFunc: AggFuncValue,
                        };
                    }
                    return { ColumnId, AggFunc };
                });
                if (!found) {
                    aggCols.push({
                        ColumnId: props.column.columnId,
                        AggFunc: AggFuncValue,
                    });
                }
                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';
    }
    const totalOptions = ['Off', 'Before', 'After', 'Pivot Specific'].map((totalVariant) => {
        return {
            label: totalVariant,
            onClick: () => {
                let aggCols = props.layout.PivotAggregationColumns;
                if (!aggCols) {
                    return;
                }
                aggCols = aggCols.map((aggCol) => {
                    if (aggCol.ColumnId === props.column.columnId) {
                        let updatedTotalColumn = false;
                        if (totalVariant === 'Before') {
                            updatedTotalColumn = 'before';
                        }
                        if (totalVariant === 'After') {
                            updatedTotalColumn = 'after';
                        }
                        if (totalVariant === 'Pivot Specific') {
                            updatedTotalColumn = props.layout.PivotColumns.map((pivotColId) => {
                                return {
                                    PivotColumnId: pivotColId,
                                    ShowTotal: true,
                                };
                            });
                        }
                        return {
                            ...aggCol,
                            Total: updatedTotalColumn,
                        };
                    }
                    return aggCol;
                });
                props.onChangeAggFunction(aggCols);
            },
        };
    });
    const currentAggCol = props.layout.PivotAggregationColumns?.find((aggCol) => aggCol.ColumnId === props.column.columnId);
    const currentTotal = currentAggCol?.Total
        ? currentAggCol.Total === true || currentAggCol.Total === 'before'
            ? 'Before'
            : currentAggCol.Total === 'after'
                ? 'After'
                : Array.isArray(currentAggCol.Total)
                    ? 'Pivot Specific'
                    : 'Off'
        : 'Off';
    const hasPivotSpecificTotals = Array.isArray(currentAggCol?.Total);
    const pivotSpecificTotals = Array.isArray(currentAggCol?.Total)
        ? currentAggCol.Total
        : props.layout.PivotColumns?.map((pivotColId) => ({
            PivotColumnId: pivotColId,
            ShowTotal: false,
        }));
    const handleTotalChange = (pivotColId, value) => {
        const updatedAggCols = (props.layout.PivotAggregationColumns || []).map((aggCol) => {
            if (aggCol.ColumnId === props.column.columnId) {
                const updatedTotals = pivotSpecificTotals.map((total) => {
                    if (total.PivotColumnId === pivotColId) {
                        return { ...total, ShowTotal: value };
                    }
                    return total;
                });
                return { ...aggCol, Total: updatedTotals };
            }
            return aggCol;
        });
        props.onChangeAggFunction(updatedAggCols);
    };
    const pivotTotalOptions = ['Off', 'Before', 'After'].map((option) => ({
        label: option,
        value: option === 'Off' ? false : option.toLowerCase(),
    }));
    return (React.createElement(Box, { "data-name": props.column.columnId, className: "ab-Layout-Wizard__ColumnRow" },
        React.createElement(Flex, { alignItems: "flex-start" },
            React.createElement(Flex, { className: "twa:flex-[0_0_auto]", alignItems: "center" },
                React.createElement(Flex, { className: "twa:min-w-[80px]" }, props.column.friendlyName),
                aggValue && (React.createElement(DropdownButton, { columns: ['label'], items: aggOptions, className: "twa:ml-2" }, currentAggFnName)),
                currentAggFnName === WEIGHTED_AVERAGE_AGG_FN_NAME && (React.createElement(Flex, { className: "twa:bg-primary twa:ml-3", alignItems: "center" },
                    React.createElement(Box, null, "Weight"),
                    ' ',
                    React.createElement(DropdownButton, { columns: ['label'], items: numericColumnsOptions, className: "twa:ml-2" }, weightName))),
                aggValue && (React.createElement(Flex, { className: "twa:bg-primary twa:ml-3", alignItems: "center" },
                    React.createElement(Box, null, "Total"),
                    ' ',
                    React.createElement(DropdownButton, { columns: ['label'], items: totalOptions, className: "twa:ml-2" }, currentTotal)))),
            hasPivotSpecificTotals && (React.createElement(Flex, { className: "twa:ml-2 twa:pl-2 twa:flex-[1_1_auto] twa:min-w-[200px]", flexWrap: "wrap", alignItems: "center", style: {
                    borderLeft: '1px solid var(--ab-color-text-on-primary)',
                    rowGap: '8px',
                    columnGap: '12px',
                } }, props.layout.PivotColumns.map((pivotColId) => {
                const pivotTotalSetting = pivotSpecificTotals.find((t) => t.PivotColumnId === pivotColId);
                const currentValue = pivotTotalSetting == undefined
                    ? 'Off'
                    : pivotTotalSetting.ShowTotal === false
                        ? 'Off'
                        : pivotTotalSetting.ShowTotal === 'before' ||
                            pivotTotalSetting.ShowTotal === true ||
                            pivotTotalSetting.ShowTotal == undefined
                            ? 'Before'
                            : pivotTotalSetting.ShowTotal === 'after'
                                ? 'After'
                                : 'Off';
                return (React.createElement(Flex, { key: pivotColId, alignItems: "center" },
                    React.createElement(Box, { className: "twa:mr-1" },
                        adaptable.api.columnApi.getFriendlyNameForColumnId(pivotColId),
                        ":"),
                    React.createElement(DropdownButton, { columns: ['label'], items: pivotTotalOptions.map((opt) => ({
                            label: opt.label,
                            onClick: () => handleTotalChange(pivotColId, opt.value),
                        })) }, currentValue)));
            }))))));
};
export const isPivotAggregationsSectionValid = (data) => {
    const weightedAvg = data.PivotAggregationColumns
        ? (data.PivotAggregationColumns || [])
            .map((agg) => agg.AggFunc)
            .find((agg) => typeof agg === 'object' && agg.type === 'weightedAverage')
        : null;
    if (weightedAvg && !weightedAvg.weightedColumnId) {
        return 'Weighted Average requires a weight column to be selected.';
    }
    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]);
    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),
                TotalColumn: currentAggColumns.find((x) => x.ColumnId === colId)?.Total,
            };
        });
        props.onChange({
            ...layout,
            PivotAggregationColumns,
        });
    }, [layout]);
    const handleAggregationChange = React.useCallback((pivotAggregationColumns) => {
        if (pivotAggregationColumns.some((aggCol) => aggCol.Total !== false || aggCol.Total !== null)) {
            // if any Aggregation Column has a Total Column, we need to disable the Pivot Group Total Column
            delete layout['PivotColumnTotal'];
        }
        props.onChange({
            ...layout,
            PivotAggregationColumns: 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,
        });
    };
    const checkIfPivotColumnTotalEnabled = () => {
        // check that all AggregationColumns have identical AggFuncs
        const aggregationColumns = layout.PivotAggregationColumns;
        if (!aggregationColumns || aggregationColumns.length === 0) {
            return true;
        }
        const firstAggFuncName = getAggFuncName(aggregationColumns[0].AggFunc);
        if (layout.PivotAggregationColumns?.some((aggCol) => getAggFuncName(aggCol.AggFunc) !== firstAggFuncName)) {
            return 'All columns must use the same aggregation function.';
        }
        // check that no Aggregation Total Column is enabled
        const hasAggregationTotalColumn = aggregationColumns.some((aggCol) => aggCol.Total !== false && aggCol.Total != null);
        if (hasAggregationTotalColumn) {
            return 'This option is not available when an Aggregation Total Column is present.';
        }
        return true;
    };
    const isPivotColumnTotalEnabled = checkIfPivotColumnTotalEnabled();
    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(FormRow, { label: 'Omit Aggregation from Header' },
                        React.createElement(CheckBox, { checked: layout.SuppressAggFuncInHeader, onChange: handleSuppressAggFuncInHeader })),
                    React.createElement(FormRow, { label: 'Grand Total Row' },
                        React.createElement(Select, { style: { width: 160 }, options: ['top', 'bottom', 'pinnedTop', 'pinnedBottom'].map((position) => {
                                return {
                                    label: StringExtensions.CamelCaseToHumanText(position),
                                    value: position,
                                };
                            }), placeholder: "[none]", value: layout.GrandTotalRow, onChange: (value) => {
                                props.onChange({
                                    ...layout,
                                    GrandTotalRow: value,
                                });
                            }, isClearable: true })),
                    React.createElement(FormRow, { label: 'Pivot Grand Total' },
                        React.createElement(Select, { className: "twa:w-[160px]", options: ['before', 'after'].map((position) => {
                                return {
                                    label: StringExtensions.CapitaliseFirstLetter(position),
                                    value: position,
                                };
                            }), placeholder: "[none]", value: layout.PivotGrandTotal, onChange: (value) => {
                                props.onChange({
                                    ...layout,
                                    PivotGrandTotal: value,
                                });
                            }, isClearable: true })),
                    React.createElement(FormRow, { label: 'Pivot Column Total' }, isPivotColumnTotalEnabled === true ? (React.createElement(Select, { style: { width: 160 }, options: ['before', 'after'].map((position) => {
                            return {
                                label: StringExtensions.CapitaliseFirstLetter(position),
                                value: position,
                            };
                        }), placeholder: "[none]", value: layout.PivotColumnTotal, onChange: (value) => {
                            props.onChange({
                                ...layout,
                                PivotColumnTotal: value,
                            });
                        }, isClearable: true })) : (React.createElement(Box, { className: "twa:ml-1 twa:italic" }, isPivotColumnTotalEnabled))))),
            React.createElement(ValueSelector, { showFilterInput: true, 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, onChange: handleColumnsSelectionChange }))));
};
