'use client';

import { string } from 'prop-types';
import React, { forwardRef, useState } from 'react';
import { IconWrapper } from '../../icon/icon-wrapper';
import { SegmentedButton } from './segmented-buttons.types';
import { ButtonLayout } from '../button-layout/button-layout';
import { ButtonLayoutProps } from '../button-layout/button-layout.types';

export const SegmentButton = forwardRef<
    HTMLButtonElement,
    ButtonLayoutProps & SegmentedButton
>(
    (
        {
            icon,
            toggled = false,
            iconPlace = 'left',
            centralRipple = false,
            ...props
        },
        ref,
    ) => {
        const {
            fillIcon,
            grade,
            svgSize,
            iconSize,
            opticalSize,
            type,
            weight,
        } = props;

        const [selectedState, setSelectedState] = useState<boolean>(false);
        const classes =
            `m3-button-segment${selectedState ? ' selected' : ''} ${props.className ?? ''}`.trimEnd();

        const _icon = selectedState && icon;

        return (
            <ButtonLayout
                {...props}
                centralRipple={centralRipple}
                className={classes}
                onClick={() => {
                    if (toggled) {
                        setSelectedState(state => !state);
                    }
                    props.onClick?.apply(this, props.onClick.arguments);
                }}
                ref={ref}
            >
                <IconWrapper
                    fillIcon={fillIcon}
                    grade={grade}
                    icon={_icon}
                    iconPlace={iconPlace}
                    iconSize={iconSize}
                    opticalSize={opticalSize}
                    svgSize={svgSize}
                    type={type}
                    weight={weight}
                >
                    <span className={'label-large'}>{props.children}</span>
                </IconWrapper>
                <span className={'m3 m3-button-segment-state-layer'} />
            </ButtonLayout>
        );
    },
);

SegmentButton.propTypes = {
    children: string,
};
