import React from 'react';
import cx from 'classnames';
import flattenChildren from 'react-keyed-flatten-children';
import { CLASSNAME } from './constants';
import { Divider } from '../divider';

type CompactProps =
    | {
          compact: true;
          applied?: boolean;
      }
    | {
          compact?: false;
          applied?: never;
      };

export type Props = {
    className?: string;
    style?: React.CSSProperties;
    testId?: string;
    children: React.ReactNode;
    disabled?: boolean;
} & CompactProps;

/**
 * SegmentedInput is a group of input fields that creates a visual connexion between the values being displayed or selected.
 *
 * @type molecule
 * @status live
 * @tags form-elements
 */
export const SegmentedInput = ({
    className,
    style,
    testId = CLASSNAME,
    children,
    disabled,
    compact,
    applied,
}: Props) => (
    <div
        className={cx(CLASSNAME, className, {
            disabled,
            [`${CLASSNAME}-compact`]: compact,
            [`${CLASSNAME}-compact-applied`]: applied,
        })}
        style={style}
        data-testid={testId}
    >
        {flattenChildren(children).map((child, index) =>
            index === 0 || !child
                ? child
                : [<Divider margin={10} key={`divider-${index}`} />, child]
        )}
    </div>
);
