'use client';

import { bool } from 'prop-types';
import { RippleEffect } from '../../ripple/ripple-effect';
import { ButtonLayoutProps } from './button-layout.types';
import useRippleEffect from '../../ripple/hooks/useRippleEffect';
import React, { forwardRef, useId, useRef, useState } from 'react';

export const ButtonLayout = forwardRef<HTMLButtonElement, ButtonLayoutProps>(
    ({ centralRipple = false, ripple = true, ...props }, ref) => {
        const [isActive, setIsActive] = useState<boolean>(false),
            ripplesRef = useRef(null),
            buttonId = useId(),
            events = useRippleEffect(ripplesRef, setIsActive, ripple);

        const extraClassStyles =
            `m3${isActive ? ' is-active' : ''} ${props.className ?? ''}`.trimEnd();

        return (
            <button
                {...props}
                {...events}
                className={extraClassStyles}
                disabled={props.disabled}
                id={buttonId}
                ref={ref}
            >
                {props.children}
                {ripple && (
                    <RippleEffect
                        callback={setIsActive}
                        central={centralRipple}
                        ref={ripplesRef}
                    />
                )}
            </button>
        );
    },
);

ButtonLayout.propTypes = {
    centralRipple: bool,
};
