import { clsx } from 'clsx';

import { ActionButtonProps } from '../actionButton/ActionButton';
import Button from '../button';
import { AriaLabelProperty, CommonProps, Heading, LinkProps, Typography } from '../common';
import Link from '../link';
import Title from '../title';

type ActionProps = AriaLabelProperty & {
  text: string;
};

type ButtonActionProps = ActionProps & ActionButtonProps;

type LinkActionProps = ActionProps & LinkProps;

export type HeaderProps = CommonProps & {
  /**
   * When the `href` property is provided to the `action`, we will render a `Link` instead of a `ActionButton`.
   */
  action?: ButtonActionProps | LinkActionProps;
  /**
   * Override the heading element rendered for the title, useful to specify the semantics of your header.
   *
   * @default "h5"
   */
  as?: Heading | 'legend';
  title: string;
};

const HeaderAction = ({ action }: { action: ButtonActionProps | LinkActionProps }) => {
  const props = {
    'aria-label': action['aria-label'],
  };

  if ('href' in action) {
    return (
      <Link href={action.href} target={action.target} onClick={action.onClick} {...props}>
        {action.text}
      </Link>
    );
  }

  return (
    <Button
      className="np-header__button"
      priority="tertiary"
      size="sm"
      onClick={action.onClick}
      {...props}
    >
      {action.text}
    </Button>
  );
};

/**
 *
 * Neptune Web: https://transferwise.github.io/neptune-web/components/content/Header
 *
 */
export const Header = ({ action, as = 'h5', title, className }: HeaderProps) => {
  if (!action) {
    return (
      <Title
        as={as}
        type={Typography.TITLE_GROUP}
        className={clsx('np-header', 'np-header__title', className)}
      >
        {title}
      </Title>
    );
  }

  if (as === 'legend') {
    // eslint-disable-next-line no-console
    console.warn(
      'Legends should be the first child in a fieldset, and this is not possible when including an action',
    );
  }

  return (
    <div className={clsx('np-header', className)}>
      <Title as={as} type={Typography.TITLE_GROUP} className="np-header__title">
        {title}
      </Title>
      <HeaderAction action={action} />
    </div>
  );
};

export default Header;
