import { clsx } from 'clsx';
import { useEffect, useRef } from 'react';

import Body from '../body/Body';
import { AriaLabelProperty, CommonProps, Typography } from '../common';
import { CloseButton } from '../common/closeButton/CloseButton';

export type ChipValue = string | number;

export type Props = {
  value?: ChipValue;
  label: string;
  onRemove?: () => void;
  onClick?: () => void;
  onKeyPress?: () => void;
  closeButton?: AriaLabelProperty;
  'aria-checked'?: boolean;
  role?: string;
} & AriaLabelProperty &
  CommonProps;

const Chip = ({
  label,
  value,
  onRemove,
  onClick,
  onKeyPress,
  className = undefined,
  'aria-label': ariaLabel,
  'aria-checked': ariaChecked,
  role,
  closeButton,
}: Props) => {
  const isActionable = onClick || onKeyPress;
  const defaultRole = isActionable ? 'button' : undefined;
  const tabIndex = isActionable ? 0 : -1;

  const closeButtonReference = useRef<HTMLButtonElement>(null);
  const previousCloseButtonShown = useRef<boolean | undefined>(undefined);
  useEffect(() => {
    if (closeButtonReference.current != null && previousCloseButtonShown.current === false) {
      closeButtonReference.current?.focus();
    }
    previousCloseButtonShown.current = closeButtonReference.current != null;
  }, [onRemove]);

  return (
    <div
      key={value}
      role={role ?? defaultRole}
      tabIndex={tabIndex}
      aria-label={ariaLabel}
      aria-checked={ariaChecked}
      className={clsx(
        'np-chip',
        'd-flex',
        'align-items-center',
        'justify-content-between',
        onRemove ? 'np-chip--removable' : '',
        className,
      )}
      {...(isActionable && { onClick, onKeyPress })}
    >
      <Body aria-hidden={!!onRemove} type={Typography.BODY_DEFAULT_BOLD}>
        {label}
      </Body>
      {onRemove ? (
        <CloseButton
          ref={closeButtonReference}
          className="btn-unstyled"
          aria-label={closeButton?.['aria-label']}
          size="sm"
          filled
          onClick={onRemove}
        />
      ) : null}
    </div>
  );
};

export default Chip;
