import { useTheme } from '@wise/components-theming';
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 { isModern } = useTheme();

  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 })}
    >
      {isModern ? (
        <Body aria-hidden={!!onRemove} type={Typography.BODY_DEFAULT_BOLD}>
          {label}
        </Body>
      ) : (
        <span aria-hidden="false" className="np-chip-label">
          {label}
        </span>
      )}
      {onRemove ? (
        <CloseButton
          ref={closeButtonReference}
          className={isModern ? `btn-unstyled` : `btn-unstyled m-l-1`}
          aria-label={closeButton?.['aria-label']}
          size="sm"
          filled={isModern}
          onClick={onRemove}
        />
      ) : null}
    </div>
  );
};

export default Chip;
