import React, { Fragment, useState, useCallback } from 'react';
import flattenChildren from 'react-keyed-flatten-children';
import cx from 'classnames';
import { CLASSNAME } from './constants';
import { SegmentedButtonContext } from './context';
import type { SegmentedButtonProps, SegmentedButtonValue } from './types';

/**
 * SegmentedButton is a group of call to actions that allows user to reorganise content according to a specific option or view.
 *
 * @type molecule
 * @status live
 * @tags buttons
 *
 * @nested Text, Glyph
 */
export const SegmentedButton = <T extends SegmentedButtonValue>({
    className,
    style,
    testId = CLASSNAME,
    value,
    defaultValue,
    onChange,
    children,
    variant = 'secondary',
    disabled = false,
}: SegmentedButtonProps<T>) => {
    const [selected, setSelected] = useState<T | undefined>(defaultValue);
    const currentValue = value === undefined ? selected : value ?? undefined;

    const handleButtonClick = useCallback(
        (value: SegmentedButtonValue) => {
            setSelected(value as T);
            onChange?.(value as T);
        },
        [onChange]
    );

    return (
        <SegmentedButtonContext.Provider
            value={{ value: currentValue, onClick: handleButtonClick, disabled }}
        >
            <div
                className={cx(className, CLASSNAME, `${CLASSNAME}-${variant}`, { disabled })}
                style={style}
                data-testid={testId}
            >
                {flattenChildren(children).map((btn, index) => (
                    <Fragment key={index}>
                        {index !== 0 && variant === 'secondary' && Boolean(btn) && (
                            <span className={`${CLASSNAME}-btn-divider`} key={`${index}-divider`} />
                        )}
                        {btn}
                    </Fragment>
                ))}
            </div>
        </SegmentedButtonContext.Provider>
    );
};
