import type {CSSProperties} from 'react';
import React from 'react';

import block from 'bem-cn-lite';
import _constant from 'lodash/constant';
import _times from 'lodash/times';

import './AutogeneratedPaletteIcon.scss';

const b = block('autogenerated-palette-icon');

type Props = {
    colors: string[];
    isGradient?: boolean;
    className?: string;
    height?: string;
    width?: string;
};

const ITEMS_PER_ROWS = 5;

const AutogeneratedPaletteIcon = (props: Props) => {
    const {colors, isGradient, className, width, height} = props;

    const rowsCount =
        colors.length < ITEMS_PER_ROWS ? 1 : Math.round(colors.length / ITEMS_PER_ROWS);

    return (
        <div className={b(null, className)} style={{height, width}}>
            {_times(rowsCount, _constant(null)).map((_el, index) => {
                const rowColors = colors.slice(
                    ITEMS_PER_ROWS * index,
                    ITEMS_PER_ROWS * (index + 1),
                );

                return (
                    <AutogeneratedPaletteIconRow
                        key={rowColors.join()}
                        rowsCount={rowsCount}
                        colors={rowColors}
                        isGradient={isGradient}
                        isFirstRow={!index}
                        isLastRow={index === rowsCount - 1}
                    />
                );
            })}
        </div>
    );
};

const FULL_ICON_WIDTH = 100;

const BORDER_RADIUS = 2;

const AutogeneratedPaletteIconRow = (props: {
    colors: string[];
    rowsCount: number;
    isGradient?: boolean;
    isFirstRow: boolean;
    isLastRow: boolean;
}) => {
    const {colors, rowsCount, isGradient, isFirstRow, isLastRow} = props;

    let styles;

    if (isGradient) {
        styles = ['135deg'].concat(colors).join();
    } else {
        styles = colors.reduce((acc, color, index) => {
            const left = (FULL_ICON_WIDTH / colors.length) * index;
            const right = (FULL_ICON_WIDTH / colors.length) * (index + 1);
            const comma = index < colors.length - 1 ? ',' : '';

            return acc + `${color} ${left}% ${right}%${comma} `;
        }, 'to right, ');
    }

    const style: CSSProperties = {
        height: `${Math.floor(100 / rowsCount)}%`,
        width: '100%',
        background: `linear-gradient(${styles})`,
        borderRadius: `${isFirstRow ? BORDER_RADIUS : 0}px ${isFirstRow ? BORDER_RADIUS : 0}px ${
            isLastRow ? BORDER_RADIUS : 0
        }px ${isLastRow ? BORDER_RADIUS : 0}px`,
    };

    return <div style={style}></div>;
};

export default AutogeneratedPaletteIcon;
