import { useContext, forwardRef } from 'react';
import { clsx } from 'clsx';
import ButtonComp, { type ButtonAddonIcon, type NewButtonProps } from '../../button';
import { useListItemControl } from '../useListItemControl';
import { ListItemContext } from '../ListItemContext';

export type ListItemButtonProps = Omit<
  NewButtonProps,
  'v2' | 'size' | 'disabled' | 'block' | 'addonStart'
> & {
  /**
   * Toggles the [interactivity strategy](https://storybook.wise.design/?path=/docs/content-listitem--docs#interactivity) for the whole ListItem.
   */
  partiallyInteractive?: boolean;
  addonStart?: ButtonAddonIcon;
  /** @default 'secondary-neutral' */
  priority?: NewButtonProps['priority'];
};

/**
 * This component allows for rendering a Button control. It's a thin wrapper around the
 * [Button component](https://storybook.wise.design/?path=/docs/content-button--docs), but offers only
 * a subset of its features in line with the ListItem's constraints. <br />
 * <br />
 * Please refer to the [Design documentation](https://docs.wise.design/components/list-item---button) for details.
 */
export const Button = forwardRef<HTMLButtonElement, ListItemButtonProps>(
  (
    { priority = 'secondary-neutral', partiallyInteractive, ...props }: ListItemButtonProps,
    ref,
  ) => {
    const { baseItemProps } = useListItemControl('button', { partiallyInteractive, ...props });
    const { ids, describedByIds } = useContext(ListItemContext);

    const commonProps = {
      ...props,
      className: clsx(
        'wds-list-item-control',
        !partiallyInteractive && props.href && 'wds-list-item-control_pseudo-element',
      ),
      id: ids.control,
      priority,
      v2: true,
      size: 'sm',
      disabled: baseItemProps.disabled,
    };

    const buttonContentId = props.href || partiallyInteractive ? '' : `${ids.control}_content`;

    return (
      <ButtonComp
        ref={ref}
        aria-describedby={`${buttonContentId} ${describedByIds}`}
        {...(commonProps as NewButtonProps)}
      />
    );
  },
);

Button.displayName = 'ListItem.Button';
