import React from 'react';

import type {SelectOptionGroup} from '@gravity-ui/uikit';
import {i18n} from 'i18n';
import type {Gradient, GradientPalettes, GradientType} from 'shared';

import AutogeneratedPaletteIcon from '../../../components/AutogeneratedPaletteIcon/AutogeneratedPaletteIcon';

function mapGradientToSelectOption(gradient: Gradient) {
    return {
        data: {
            icon: (
                <AutogeneratedPaletteIcon
                    colors={gradient.colors}
                    isGradient={true}
                    height="16px"
                    width="20px"
                />
            ),
        },
        content: gradient.title || i18n('wizard', `label_${gradient.id as GradientType}`),
        value: gradient.id,
    };
}

export const getGradientSelectorItems = (
    gradients: GradientPalettes,
): SelectOptionGroup<{icon: JSX.Element}>[] => {
    const basePalettes: Gradient[] = [];
    const namedPalettes: Gradient[] = [];

    Object.values(gradients).forEach((item) => {
        if (item.title) {
            namedPalettes.push(item);
        } else {
            basePalettes.push(item);
        }
    });

    const result: SelectOptionGroup<{icon: JSX.Element}>[] = [];
    if (basePalettes.length) {
        result.push({
            label: '',
            options: basePalettes.map(mapGradientToSelectOption),
        });
    }

    if (namedPalettes.length) {
        result.push({
            label: '',
            options: namedPalettes.map(mapGradientToSelectOption),
        });
    }

    return result;
};
