'use client';

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

/**
 * Segment button
 */

export const SegmentButton = forwardRef<
    HTMLButtonElement,
    ButtonLayoutProps & SegmentedButton
>(
    (
        {
            type,
            icon,
            grade,
            weight,
            svgSize,
            fillIcon,
            children,
            iconSize,
            opticalSize,
            selectable = false,
            iconPlace = 'left',
            centralRipple = false,
            ...props
        },
        ref,
    ) => {
        const [selectedState, setSelectedState] = useState<boolean>(false);
        const classes =
            `m3-button-segment${selectedState ? ' selected' : ''} ${props.className ?? ''}`.trimEnd();

        const ButtonLabel = (
            <Typography className={'label-large'} role={'label'} size={'large'}>
                {children}
            </Typography>
        );

        const iconProps = {
            grade: grade,
            fillIcon: fillIcon,
            iconSize: iconSize,
            opticalSize: opticalSize,
            svgSize: svgSize,
            type: type,
            weight: weight,
        };

        return (
            <ButtonLayout
                {...props}
                centralRipple={centralRipple}
                className={classes}
                onClick={() => {
                    if (selectable) {
                        setSelectedState(state => !state);
                    }
                    props.onClick?.apply(this, props.onClick.arguments);
                }}
                ref={ref}
            >
                <span className={'m3 m3-button-segment-content-layer'}>
                    <IconWrapper
                        {...iconProps}
                        icon={icon}
                        iconPlace={iconPlace}
                    >
                        {ButtonLabel}
                    </IconWrapper>
                </span>
                <span className={'m3 m3-button-segment-state-layer'}>
                    {selectable && (
                        <>
                            <Icon {...iconProps}>{icon}</Icon>
                            {ButtonLabel}
                        </>
                    )}
                </span>
            </ButtonLayout>
        );
    },
);

SegmentButton.propTypes = {
    children: string,
};
