import React, { useState } from 'react';
import cx from 'classnames';
import { HiddenCount } from '../hiddenCount';
import { Pill } from '../pill';
import type { ComponentBaseProps } from '../../types';
import type { PillProps } from '../pill';

const CLASS_NAME = 'PillCloud';

export interface Props extends ComponentBaseProps {
    style?: React.CSSProperties;
    disableExpand?: boolean;
    pillsProps: PillProps[];
    itemWidth?: number | string;
    itemMaxWidth?: number | string;
    maxVisibleCount?: number;
}

/**
 * PillCloud is an expandable container of Pill components.
 *
 * @type molecule
 * @status live
 * @tags utilities
 */
export const PillCloud: React.FC<Props> = ({
    disableExpand,
    className,
    style,
    testId = CLASS_NAME,
    pillsProps = [],
    maxVisibleCount = 5,
    itemWidth,
    itemMaxWidth,
}) => {
    const [expanded, setExpanded] = useState(false);

    const visiblePills = expanded ? pillsProps : pillsProps.slice(0, maxVisibleCount);
    const hiddenCount = pillsProps.length - visiblePills.length;

    const toggleExpanded = () => {
        if (!disableExpand) setExpanded(!expanded);
    };

    return (
        <div className={cx(CLASS_NAME, className)} style={style} data-testid={testId}>
            {visiblePills.map((pillProps) => (
                <Pill
                    className={`${CLASS_NAME}-pill`}
                    key={pillProps.popoverOptions.id}
                    width={itemWidth}
                    maxWidth={itemMaxWidth}
                    {...pillProps}
                />
            ))}

            {pillsProps.length > maxVisibleCount && (
                <HiddenCount
                    doubleChevron
                    expanded={expanded}
                    hiddenCount={hiddenCount}
                    showExpander={disableExpand || pillsProps.length > maxVisibleCount}
                    onClick={toggleExpanded}
                />
            )}
        </div>
    );
};
