import * as React from 'react';
import { useMemo, useEffect, useState } from 'react';
import { Loader } from '../../../components/Loader';
import { Tabs } from '../../../components/Tabs';
import join from '../../../components/utils/join';
import { runIfNotResolvedIn } from '../../../Utilities/runIfNotResolvedIn';
import { ValueSelector } from '../../Components/ValueSelector';
import { useOnePageAdaptableWizardContext } from '../../Wizard/OnePageAdaptableWizard';
import ArrayExtensions from '../../.././Utilities/Extensions/ArrayExtensions';
import { parseToISO } from '../../../Utilities/Helpers/DateHelper';
import { TagList } from '../../../components/Tag';
export const isValidCustomSortOrder = (data) => {
    if (!data.SortedValues || !data.SortedValues.length) {
        return 'You have to specify at least one value for Custom Sort order';
    }
    return true;
};
export const renderCustomSortValuesSummary = (data) => {
    return React.createElement(TagList, { tags: data.SortedValues.map(String) });
};
export const CustomSortValuesWizardSection = (props) => {
    const { data, api } = useOnePageAdaptableWizardContext();
    const [distinctValues, setDistinctValues] = useState([]);
    const [isDistinctValuesLoading, setIsDistinctValuesLoading] = useState(false);
    const columnDataType = api.columnApi.getColumnDataTypeForColumnId(data.ColumnId);
    useEffect(() => {
        let isMounted = true;
        (async () => {
            // for sync and very fast resolving promises does not make sense to show a loader
            setDistinctValues([]);
            const newValues = (await runIfNotResolvedIn(api.gridApi.internalApi.getDistinctValuesForColumn(data.ColumnId), () => isMounted && setIsDistinctValuesLoading(true))) ?? [];
            if (!isMounted) {
                return;
            }
            setIsDistinctValuesLoading(false);
            setDistinctValues(newValues);
        })();
        return () => {
            isMounted = false;
        };
    }, [data.ColumnId]);
    const toIdentifier = (optionItem) => {
        return api.customSortApi.internalApi.getCustomSortValue(optionItem, columnDataType);
    };
    const toLabel = (optionItem) => {
        return `${optionItem}`;
    };
    const sortedValuesMap = useMemo(() => {
        if (!data.SortedValues || !data.SortedValues.length) {
            return new Map();
        }
        return data.SortedValues.reduce((acc, val) => {
            acc.set(val, true);
            return acc;
        }, new Map());
    }, [data.SortedValues]);
    const allowReorder = React.useCallback((option) => {
        return sortedValuesMap.has(toIdentifier(option));
    }, [sortedValuesMap]);
    const getOptionValues = (gridCells) => {
        return gridCells.map((gridCell) => {
            return columnDataType === 'date' ? parseToISO(gridCell.rawValue) : gridCell.normalisedValue;
        });
    };
    const options = useMemo(() => {
        return ArrayExtensions.sortArrayWithOrder(getOptionValues(distinctValues), data.SortedValues, {
            sortUnorderedItems: false,
        });
    }, [allowReorder, distinctValues, data.SortedValues]);
    const baseClassName = 'ab-CustomSortWizard__SortOrder';
    const className = join(baseClassName, isDistinctValuesLoading && `${baseClassName}--loading`);
    return (React.createElement(Tabs, { style: { height: '100%' }, className: className },
        React.createElement(Tabs.Tab, null, "Sort Order"),
        React.createElement(Tabs.Content, null,
            isDistinctValuesLoading && React.createElement(Loader, null, "Loading"),
            React.createElement(ValueSelector, { toIdentifier: toIdentifier, toLabel: toLabel, options: options, value: data.SortedValues, allowReorder: allowReorder, onChange: (SortedValues) => {
                    props.onChange({
                        ...data,
                        SortedValues,
                    });
                } }))));
};
