import * as React from 'react';
import { CheckBox } from '../../../../components/CheckBox';
import ErrorBox from '../../../../components/ErrorBox';
import FormLayout, { FormRow } from '../../../../components/FormLayout';
import { Tag } from '../../../../components/Tag';
import { ColorPicker } from '../../../../components/ColorPicker';
import { RangesComponent } from '../../../Components/RangesComponent';
import { StyleVisualItem } from '../../../Components/StyleVisualItem';
import { getHexForName, GRAY } from '../../../UIHelper';
import { useOnePageAdaptableWizardContext } from '../../../Wizard/OnePageAdaptableWizard';
import { PercentBarColumnComparisonPreview } from './Components/PercentBarColumnComparisonPreview';
import { PercentBarPreview } from './Components/PercentBarRangesPreview';
import DropdownButton from '../../../../components/DropdownButton';
import ArrayExtensions from '../../../../Utilities/Extensions/ArrayExtensions';
import { Box, Flex } from '../../../../components/Flex';
export const renderFormatColumnStyleWizardSummary = (data) => {
    const { api } = useOnePageAdaptableWizardContext();
    return renderStyledColumnStyleSummary(data, api);
};
const getRanges = (ranges, rangeValueType) => {
    let postfix = '';
    if (rangeValueType === 'Percentage') {
        postfix = '%';
    }
    return ranges.map((r, i) => (React.createElement(Flex, { key: i, alignItems: "center", className: "twa:mr-3" },
        React.createElement(Box, { className: "twa:mr-1" },
            r.Min,
            postfix,
            " to ",
            r.Max,
            postfix),
        React.createElement(StyleVisualItem, { Style: {
                BackColor: r.Color,
                ForeColor: r.Color,
            } }))));
};
const getColumnComparison = (columnComparison, api) => {
    return (React.createElement(Flex, { key: 'cc', alignItems: "center", className: "twa:mr-3" },
        React.createElement(Box, { className: "twa:mr-1" },
            "Min Value:",
            ' ',
            isNaN(Number(columnComparison.MinValue))
                ? '[' + api.columnApi.getFriendlyNameForColumnId(String(columnComparison.MinValue)) + ']'
                : columnComparison.MinValue,
            ' ',
            ", Max Value:",
            ' ',
            isNaN(Number(columnComparison.MaxValue))
                ? '[' + api.columnApi.getFriendlyNameForColumnId(String(columnComparison.MaxValue)) + ']'
                : columnComparison.MaxValue,
            ' '),
        React.createElement(StyleVisualItem, { Style: {
                BackColor: columnComparison.Color,
                ForeColor: columnComparison.Color,
            } })));
};
export const renderStyledColumnStyleSummary = (data, api) => {
    if (!api) {
        const { api: adaptableApi } = useOnePageAdaptableWizardContext();
        api = adaptableApi;
    }
    if (data.GradientStyle) {
        if (data.GradientStyle.CellRanges) {
            return getRanges(data.GradientStyle.CellRanges, data.GradientStyle.RangeValueType);
        }
        if (data.GradientStyle.ColumnComparison) {
            return getColumnComparison(data.GradientStyle.ColumnComparison, api);
        }
    }
    if (data.PercentBarStyle) {
        if (data.PercentBarStyle.ColumnComparison) {
            return React.createElement(PercentBarColumnComparisonPreview, { percentBarStyle: data.PercentBarStyle });
        }
        if (data.PercentBarStyle.CellRanges) {
            return React.createElement(PercentBarPreview, { percentBarStyle: data.PercentBarStyle });
        }
    }
    return React.createElement(Tag, null, "No Styling Defined");
};
export const StyledColumnWizardStyleSection = (props) => {
    const { data, api } = useOnePageAdaptableWizardContext();
    const minMaxRangeValues = React.useMemo(() => {
        const columnId = data.ColumnId;
        if (!columnId) {
            return null;
        }
        const column = api.columnApi.getColumnWithColumnId(columnId);
        return {
            min: api.styledColumnApi.internalApi.getMinValueForNumericColumn(column),
            max: api.styledColumnApi.internalApi.getMaxValueForNumericColumn(column),
        };
    }, [data]);
    const scope = { ColumnIds: [data.ColumnId] }; // TODO: remove scope when format column columnStyle is removed
    // gradient
    const onUpdateGradientStyleRanges = (ranges) => {
        const gradientStyle = {
            ...data.GradientStyle,
            CellRanges: ranges,
        };
        // delete gradientStyle.ColumnComparison in case we are switching from ColumnComparison to CellRanges
        delete gradientStyle.ColumnComparison;
        props.onChange({ ...data, GradientStyle: gradientStyle });
    };
    const onUpdateGradientStyleColumnComparison = (columnComparison) => {
        const GradientStyle = {
            ColumnComparison: columnComparison,
        };
        props.onChange({ ...data, GradientStyle });
    };
    // percentbar
    const onUpdatePercentBarStyleColumnComparison = (columnComparison) => {
        const PercentBarStyle = {
            ...data.PercentBarStyle,
            ColumnComparison: columnComparison,
        };
        props.onChange({ ...data, PercentBarStyle });
    };
    const onUpdatePercentBarStyleRanges = (ranges) => {
        const PercentBarStyle = {
            ...data.PercentBarStyle,
            CellRanges: ranges,
        };
        props.onChange({ ...data, PercentBarStyle });
    };
    const onPercentBarCellTextCellValueChanged = (checked) => {
        let percentBarStyle = data?.PercentBarStyle;
        if (checked) {
            if (!percentBarStyle.CellText) {
                percentBarStyle.CellText = ['CellValue'];
            }
            else {
                percentBarStyle.CellText.push('CellValue');
            }
        }
        else {
            if (percentBarStyle.CellText && percentBarStyle.CellText.includes('PercentageValue')) {
                percentBarStyle.CellText = ['PercentageValue'];
            }
            else {
                percentBarStyle.CellText = [];
            }
        }
        props.onChange({
            ...data,
            PercentBarStyle: percentBarStyle,
        });
    };
    const onPercentBarCellTextPercentValueChanged = (checked) => {
        let percentBarStyle = data?.PercentBarStyle;
        if (checked) {
            if (!percentBarStyle.CellText) {
                percentBarStyle.CellText = ['PercentageValue'];
            }
            else {
                percentBarStyle.CellText.push('PercentageValue');
            }
        }
        else {
            if (percentBarStyle.CellText && percentBarStyle.CellText.includes('CellValue')) {
                percentBarStyle.CellText = ['CellValue'];
            }
            else {
                percentBarStyle.CellText = [];
            }
        }
        props.onChange({
            ...data,
            PercentBarStyle: percentBarStyle,
        });
    };
    const handlePercentBarCellTextPositionChange = (percentBarPosition) => {
        props.onChange({
            ...data,
            PercentBarStyle: {
                ...data.PercentBarStyle,
                CellTextPosition: percentBarPosition,
            },
        });
    };
    const onPercentBarToolTipTextCellValueChanged = (checked) => {
        let percentBarStyle = data?.PercentBarStyle;
        if (checked) {
            if (!percentBarStyle.ToolTipText) {
                percentBarStyle.ToolTipText = ['CellValue'];
            }
            else {
                percentBarStyle.ToolTipText.push('CellValue');
            }
        }
        else {
            if (percentBarStyle.ToolTipText && percentBarStyle.ToolTipText.includes('PercentageValue')) {
                percentBarStyle.ToolTipText = ['PercentageValue'];
            }
            else {
                percentBarStyle.ToolTipText = [];
            }
        }
        props.onChange({
            ...data,
            PercentBarStyle: percentBarStyle,
        });
    };
    const onPercentBarToolTipTextPercentValueChanged = (checked) => {
        let percentBarStyle = data.PercentBarStyle;
        if (checked) {
            if (!percentBarStyle.ToolTipText) {
                percentBarStyle.ToolTipText = ['PercentageValue'];
            }
            else {
                percentBarStyle.ToolTipText.push('PercentageValue');
            }
        }
        else {
            if (percentBarStyle.ToolTipText && percentBarStyle.ToolTipText.includes('CellValue')) {
                percentBarStyle.ToolTipText = ['CellValue'];
            }
            else {
                percentBarStyle.ToolTipText = [];
            }
        }
        props.onChange({
            ...data,
            PercentBarStyle: percentBarStyle,
        });
    };
    const onUsePercentStyleColorCheckChanged = (checked) => {
        let percentBarStyle = data?.PercentBarStyle;
        percentBarStyle.BackColor = checked ? getHexForName(GRAY) : null;
        props.onChange({
            ...data,
            PercentBarStyle: percentBarStyle,
        });
    };
    const onForeColorSelectChange = (color) => {
        let percentBarStyle = data.PercentBarStyle;
        percentBarStyle.BackColor = color;
        props.onChange({
            ...data,
            PercentBarStyle: percentBarStyle,
        });
    };
    const handleRangeValueTypeChange = React.useCallback((rangeValueType) => {
        const ranges = rangeValueType === 'Number'
            ? api.columnScopeApi.createCellColorRangesForScope(scope)
            : [
                {
                    Min: 0,
                    Max: 100,
                    Color: getHexForName(GRAY),
                },
            ];
        let newStyledColumn = data;
        const commonStyle = {
            CellRanges: ranges,
            RangeValueType: rangeValueType,
        };
        if ('GradientStyle' in newStyledColumn) {
            newStyledColumn = {
                ...newStyledColumn,
                GradientStyle: {
                    ...newStyledColumn.GradientStyle,
                    ...commonStyle,
                },
            };
        }
        else {
            newStyledColumn = {
                ...newStyledColumn,
                PercentBarStyle: {
                    ...newStyledColumn.PercentBarStyle,
                    ...commonStyle,
                },
            };
        }
        props.onChange(newStyledColumn);
    }, [data]);
    const disabled = !data.ColumnId;
    return (React.createElement(Box, null,
        data?.GradientStyle && (React.createElement(RangesComponent, { disabled: !data.ColumnId, minMaxRangeValues: minMaxRangeValues, api: api, scope: scope, showRangeDirection: true, ranges: data.GradientStyle?.CellRanges, rangeValueType: data.GradientStyle?.RangeValueType, onRangeValueTypeChange: handleRangeValueTypeChange, columnComparison: data?.GradientStyle?.ColumnComparison, updateRanges: (ranges) => onUpdateGradientStyleRanges(ranges), updateColumnComparison: (columnComparison) => onUpdateGradientStyleColumnComparison(columnComparison) })),
        data.PercentBarStyle && (React.createElement(React.Fragment, null,
            React.createElement(RangesComponent, { disabled: disabled, minMaxRangeValues: minMaxRangeValues, api: api, scope: scope, showRangeDirection: false, ranges: data.PercentBarStyle?.CellRanges, rangeValueType: data.PercentBarStyle?.RangeValueType, onRangeValueTypeChange: handleRangeValueTypeChange, columnComparison: data?.PercentBarStyle?.ColumnComparison, updateRanges: (ranges) => onUpdatePercentBarStyleRanges(ranges), updateColumnComparison: (columnComparison) => onUpdatePercentBarStyleColumnComparison(columnComparison) }),
            React.createElement(FormLayout, { className: "twa:mt-2 twa:ml-2" },
                React.createElement(FormRow, { label: "Cell Display:" },
                    React.createElement(CheckBox, { disabled: disabled, className: "twa:ml-2", checked: data.PercentBarStyle?.CellText?.includes('CellValue'), onChange: (checked) => onPercentBarCellTextCellValueChanged(checked) }, "Cell Value"),
                    ' ',
                    React.createElement(CheckBox, { disabled: disabled, className: "twa:ml-3", checked: data?.PercentBarStyle?.CellText?.includes('PercentageValue'), onChange: (checked) => onPercentBarCellTextPercentValueChanged(checked) },
                        "Percent Value",
                        ' '),
                    ' '),
                React.createElement(FormRow, { label: "Cell Display Position:" },
                    React.createElement(DropdownButton, { disabled: ArrayExtensions.IsNullOrEmpty(data.PercentBarStyle.CellText) || disabled, columns: ['label'], items: [
                            {
                                label: 'Above Bar',
                                onClick: () => handlePercentBarCellTextPositionChange('Above'),
                            },
                            {
                                label: 'Below Bar',
                                onClick: () => handlePercentBarCellTextPositionChange('Below'),
                            },
                            {
                                label: 'Merged',
                                onClick: () => handlePercentBarCellTextPositionChange('Merged'),
                            },
                        ] }, data.PercentBarStyle?.CellTextPosition ?? 'Below')),
                React.createElement(FormRow, { label: "ToolTip Display:" },
                    React.createElement(CheckBox, { disabled: disabled, className: "twa:ml-2", checked: data?.PercentBarStyle?.ToolTipText?.includes('CellValue'), onChange: (checked) => onPercentBarToolTipTextCellValueChanged(checked) }, "Cell Value"),
                    ' ',
                    React.createElement(CheckBox, { disabled: disabled, className: "twa:ml-3", checked: data?.PercentBarStyle?.ToolTipText?.includes('PercentageValue'), onChange: (checked) => onPercentBarToolTipTextPercentValueChanged(checked) },
                        "Percent Value",
                        ' '),
                    ' '),
                React.createElement(FormRow, { label: `Back ${api.internalApi.getCorrectEnglishVariant('Colour')}` },
                    React.createElement(Flex, { alignItems: "center", className: "twa:ml-2" },
                        React.createElement(CheckBox, { disabled: disabled, checked: !!data.PercentBarStyle?.BackColor, onChange: (checked) => onUsePercentStyleColorCheckChanged(checked), className: "twa:mr-2" }),
                        data.PercentBarStyle?.BackColor !== undefined && (React.createElement(ColorPicker, { disabled: disabled, api: api, value: data.PercentBarStyle?.BackColor, onChange: (x) => onForeColorSelectChange(x) }))))))),
        !data.ColumnId && (React.createElement(ErrorBox, { className: "twa:mt-2" }, "You need to select a column before styling."))));
};
