import { QuestionMarkCircle as HelpCircleIcon } from '@transferwise/icons';
import { clsx } from 'clsx';
import { useState } from 'react';
import { useIntl } from 'react-intl';

import { Size, Position, SizeSmall, SizeLarge } from '../common';
import Modal from '../modal';
import Popover, { PopoverPreferredPlacement } from '../popover';

import messages from './Info.messages';
import { InfoPresentation } from './infoPresentations';

export interface InfoProps {
  'aria-label'?: string;
  /**
   * Extra classes applied to Info
   */
  className?: string;
  /**
   * Content displayed inside a Popover a Modal
   */
  content?: React.ReactNode;
  onClick?: () => void;
  /**
   * Decides whether to display content in a Popover or a Modal
   */
  presentation?: 'MODAL' | 'POPOVER';
  /**
   * Decides the size of help Icon
   */
  size?: SizeSmall | SizeLarge;
  /**
   * Title displayed inside a Popover a Modal
   */
  title?: React.ReactNode;
  /**
   * Prferred placement of the Popover, does not apply to Modal
   */
  preferredPlacement?: PopoverPreferredPlacement;
}

const Info = ({
  className = undefined,
  content = undefined,
  onClick = undefined,
  presentation = InfoPresentation.POPOVER,
  size = Size.SMALL,
  title = undefined,
  'aria-label': ariaLabel,
  preferredPlacement = Position.BOTTOM,
}: InfoProps) => {
  const intl = useIntl();
  const [open, setOpen] = useState(false);
  ariaLabel ??= intl.formatMessage(messages.ariaLabel);
  const isModal = presentation === InfoPresentation.MODAL;
  const isSmall = size === Size.SMALL;

  const buttonProps = {
    'aria-label': ariaLabel,
    className: 'btn-unstyled',
    children: <HelpCircleIcon size={isSmall ? 16 : 24} />,
  };

  return (
    <span
      className={clsx(className, 'np-info', {
        'np-info__small': isSmall,
        'np-info__large': !isSmall,
      })}
    >
      {isModal ? (
        <>
          <button
            type="button"
            onClick={() => {
              setOpen(!open);
              if (onClick) {
                onClick();
              }
            }}
            {...buttonProps}
          />
          <Modal body={content} open={open} title={title} onClose={() => setOpen(false)} />
        </>
      ) : (
        <Popover content={content} preferredPlacement={preferredPlacement} title={title}>
          <button
            type="button"
            {...buttonProps}
            onClick={() => {
              if (onClick) {
                onClick();
              }
            }}
          />
        </Popover>
      )}
    </span>
  );
};

export default Info;
