import * as React from 'react';
import clsx from 'clsx';
import { IconComponent } from '../Icon';
import { twMerge } from '../../twMerge';
import { ToggleGroupContext } from './ToggleGroup';
const baseClassName = 'ab-Toggle';
export const Toggle = ({ onPressedChange, pressed, icon, children, ...rest }) => {
    const onPressedChangeRef = React.useRef(onPressedChange);
    React.useLayoutEffect(() => {
        onPressedChangeRef.current = onPressedChange;
    }, [onPressedChange]);
    const pressedRef = React.useRef(pressed);
    React.useLayoutEffect(() => {
        pressedRef.current = pressed;
    }, [pressed]);
    const toggle = React.useCallback(() => onPressedChangeRef.current(!pressedRef.current), []);
    const toggleContext = React.useContext(ToggleGroupContext);
    const [currentIndex, setCurrentIndex] = React.useState(-1);
    const isActive = toggleContext.activeIndex === currentIndex;
    const ref = React.useRef(null);
    React.useEffect(() => {
        if (!toggleContext || !toggleContext.toggleButtons) {
            return;
        }
        const thisButton = {
            node: ref.current,
            toggle,
        };
        toggleContext.toggleButtons.push(thisButton);
        setCurrentIndex(toggleContext.toggleButtons.length - 1);
        return () => {
            const index = toggleContext.toggleButtons.indexOf(thisButton);
            if (index !== -1) {
                toggleContext.toggleButtons.splice(index, 1);
            }
        };
    }, [toggleContext]);
    return (React.createElement("button", { ...rest, ref: ref, tabIndex: -1, className: twMerge(clsx('twa:border-0', 'twa:cursor-pointer twa:fill-current', 'twa:outline-0', 'twa:min-h-input twa:relative twa:py-1 twa:px-2', 'twa:not-first:after:content-[""] twa:not-first:after:border-l-2 twa:not-first:after:border-accent-foreground twa:not-first:after:h-[10px] twa:not-first:after:absolute twa:not-first:after:-left-px twa:not-first:after:top-1/2 twa:not-first:after:-translate-y-1/2', 
        // backgrounds
        {
            'twa:text-inherit twa:bg-transparent': !pressed,
            'twa:hover:bg-primarylight twa:hover:text-text-on-primary': !pressed,
            [`${baseClassName}--pressed`]: pressed,
            'twa:bg-accent twa:hover:bg-accent/90 twa:text-accent-foreground': pressed,
        }, {
            'twa:before:rounded-standard twa:before:content-[""] twa:before:absolute twa:before:inset-1 twa:before:z-20 twa:before:pointer-events-none': true,
            // let's display a shadow on the before pseudo element
            // when the toggle is active
            'twa:before:shadow-(--ab-focus-light__box-shadow)': isActive && pressed,
            'twa:before:shadow-(--ab-focus__box-shadow)': isActive && !pressed,
        }, baseClassName)), onClick: toggle },
        icon && React.createElement(IconComponent, { icon: { name: icon } }),
        children));
};
