import type { FC } from 'react';
import React from 'react';
import cx from 'classnames';
import { Button } from '../bootstrap';
import type { ComponentBaseProps } from '../../types';
import type { ButtonProps } from '../bootstrap';

export const CLASS_NAME = 'ToggleButton';

export type ToggleButtonProps = Omit<ButtonProps, 'onChange' | 'defaultValue'> &
    ComponentBaseProps & {
        /**
         * Sets the initial toggle state
         */
        defaultValue?: boolean;

        /**
         * Defines a controlled state for the button
         */
        value?: boolean;

        /**
         * Callback with the new state of the button
         */
        onChange: (newState: boolean) => void;
    };

/**
 * ToggleButton is a button that can be turned on and off and will change colour to indicate its state.
 *
 * @type atom
 * @status live
 * @tags buttons
 */
export const ToggleButton: FC<ToggleButtonProps> = ({
    className,
    testId = CLASS_NAME,
    defaultValue = false,
    value,
    disabled = false,
    onChange,
    ...props
}) => {
    const [tgg, setToggled] = React.useState(value ?? defaultValue);
    const toggled = value ?? tgg;

    return (
        <Button
            {...props}
            data-testid={testId}
            disabled={disabled}
            variant={toggled ? 'secondary' : 'tertiary'}
            className={cx(CLASS_NAME, className, {
                toggled,
                disabled,
            })}
            onClick={() => {
                const newState = !toggled;
                setToggled(newState);
                onChange(newState);
            }}
        />
    );
};
