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';
import IconButton, { IconButtonProps } from '../iconButton';

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 buttonProps: IconButtonProps = {
    'aria-label': ariaLabel,
    priority: 'minimal',
    size: 24,
    children: <HelpCircleIcon />,
  };

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

export default Info;
