import styles from './index.module.scss';
import ContentFields from './ContentFields.js';
import StyleFields from './StyleFields.js';
import cx from '../utils/classname.js';
import { LinkProps, BaseLinkProps, LinkHTMLProps } from './types.js';
import {
  getLinkRel,
  getLinkFieldTarget,
  getLinkFieldRel,
} from '../utils/linkField.js';

const getLinkValues = (props: Omit<LinkProps, keyof BaseLinkProps>) => {
  let href: string;
  let target: '_self' | '_blank' | '_parent' | '_top';
  let relValues: string | undefined;
  let anchorProps: LinkHTMLProps;

  // if linkField was passed in, use it for attrs; otherwise, build up link attrs from props
  if ('linkField' in props && props.linkField) {
    const { linkField, ...otherProps } = props;
    href = linkField.url?.href || '';
    target = getLinkFieldTarget(linkField);
    relValues = getLinkFieldRel(linkField);
    anchorProps = otherProps;
  } else {
    ({ href = '', target = '_self', ...anchorProps } = props);
    relValues = getLinkRel(target, props.rel);
  }

  return { href, target, rel: relValues, anchorProps };
};

const LinkComponent = ({
  variant = 'primaryLink',
  className = '',
  style = {},
  children,
  ...rest
}: LinkProps) => {
  const { href, target, rel, anchorProps } = getLinkValues(rest);

  const defaultClasses = styles.link;
  const combinedClasses = cx(defaultClasses, className);

  return (
    <a
      className={combinedClasses}
      style={style}
      href={href}
      target={target}
      rel={rel}
      data-link-variant={variant}
      {...anchorProps}
    >
      {children}
    </a>
  );
};

type LinkComponentType = typeof LinkComponent & {
  ContentFields: typeof ContentFields;
  StyleFields: typeof StyleFields;
};

const Link = LinkComponent as LinkComponentType;
Link.ContentFields = ContentFields;
Link.StyleFields = StyleFields;

export default Link;
