import { clsx } from 'clsx';
import { useContext, type ReactNode } from 'react';
import IconButtonComp, { type IconButtonProps } from '../../iconButton';
import { useListItemControl } from '../useListItemControl';
import { ListItemContext } from '../ListItemContext';

export type ListItemIconButtonProps = Pick<
  IconButtonProps,
  'type' | 'onClick' | 'href' | 'target' | 'aria-label'
> & {
  children: ReactNode;
  partiallyInteractive?: boolean;
  /** @default 'minimal' */
  priority?: IconButtonProps['priority'];
};

/**
 * This component allows for rendering a IconButton control. It's a thin wrapper around the
 * [IconButton component](https://storybook.wise.design/?path=/docs/actions-iconbutton--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://wise.design/components/list-item---icon-button) for details.
 */
export const IconButton = function ({
  priority = 'minimal',
  'aria-label': ariaLabel,
  ...props
}: ListItemIconButtonProps) {
  const { partiallyInteractive, ...restProps } = props;

  const { ids, props: itemProps } = useContext(ListItemContext);
  const { baseItemProps } = useListItemControl('icon-button', {
    partiallyInteractive,
    ...restProps,
  });

  const getAriaProps = () => {
    const labelIds = [
      itemProps.inverted ? ids.subtitle : ids.title,
      itemProps.inverted ? ids.title : ids.subtitle,
      itemProps.inverted ? ids.valueSubtitle : ids.valueTitle,
      itemProps.inverted ? ids.valueTitle : ids.valueSubtitle,
    ].join(' ');
    const descriptorIds = [ids.additionalInfo, ids.prompt].join(' ');

    if (ariaLabel) {
      return {
        'aria-label': ariaLabel,
        'aria-describedby': labelIds.concat(descriptorIds),
      };
    }

    return {
      'aria-labelledby': labelIds,
      'aria-describedby': descriptorIds,
    };
  };

  return (
    <IconButtonComp
      {...restProps}
      {...getAriaProps()}
      className={clsx(
        'wds-list-item-control',
        !partiallyInteractive && props.href && 'wds-list-item-control_pseudo-element',
      )}
      id={ids.control}
      size={40}
      priority={priority}
      disabled={baseItemProps.disabled}
    />
  );
};

IconButton.displayName = 'ListItem.IconButton';
