import { Icon, type ApprovedIconName } from '@/components/foundation/Icon';
import { classNames } from '@/lib/components/classNames';
import type { AnchorHTMLAttributes, ReactNode } from 'react';
import styles from './ActionLink.module.css';

type LinkVariant =
  | 'inline'
  | 'navigation'
  | 'standalone'
  | 'button-primary'
  | 'button-conversion'
  | 'muted';

interface ActionLinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
  href: string;
  children: ReactNode;
  variant?: LinkVariant;
  icon?: ApprovedIconName;
  external?: boolean;
  newTab?: boolean;
  disabledReason?: string;
}

export function ActionLink({
  href,
  children,
  variant = 'inline',
  icon,
  external = false,
  newTab = false,
  disabledReason,
  className,
  ...props
}: ActionLinkProps) {
  if (disabledReason) {
    return (
      <span
        className={classNames(styles.link, styles[variant], styles.disabled, className)}
        aria-disabled="true"
        title={disabledReason}
      >
        <span>{children}</span>
        <span className="visually-hidden">: {disabledReason}</span>
      </span>
    );
  }
  const isExternal = external || /^https?:\/\//.test(href);
  const trailingIcon = icon ?? (isExternal ? 'external' : undefined);
  const content = (
    <>
      <span>{children}</span>
      {trailingIcon ? (
        <Icon
          name={trailingIcon}
          size="sm"
          directionBehavior={
            trailingIcon === 'chevron-forward' || trailingIcon === 'arrow-forward'
              ? 'mirror'
              : 'fixed'
          }
        />
      ) : null}
      {newTab ? <span className="visually-hidden"> (opens in a new tab)</span> : null}
    </>
  );
  const shared = {
    className: classNames(styles.link, styles[variant], className),
    ...(newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}),
    ...props,
  };
  return (
    <a href={href} {...shared}>
      {content}
    </a>
  );
}
