import * as React from "react";
// import NextLink, { LinkProps } from "next/link";
import MuiLink, { LinkProps } from "@mui/material/Link";

import { generateUtmQueriesStr, getUrlHash } from "@/utils";

export interface UTMLinkProps extends LinkProps {
  utmSource?: string;
  utmMedium?: string;
  utmCampaign?: string;
  utmContent?: string;
  utmTerm?: string;
}

export default function UTMLink(props: UTMLinkProps) {
  const {
    href,
    utmSource,
    utmMedium,
    utmCampaign,
    utmContent,
    utmTerm,
    ...other
  } = props;

  const hrefMemo = React.useMemo(() => {
    if (!href) return href;

    const utmParams: { [x: string]: string } = {};
    utmCampaign && (utmParams["utm_campaign"] = utmCampaign);
    utmContent && (utmParams["utm_content"] = utmContent);
    utmMedium && (utmParams["utm_medium"] = utmMedium);
    utmSource && (utmParams["utm_source"] = utmSource);
    utmTerm && (utmParams["utm_term"] = utmTerm);

    const hash = getUrlHash(href);

    const hrefWithoutHash = hash ? href.slice(0, -hash.length - 1) : href;

    return `${hrefWithoutHash}?${generateUtmQueriesStr(utmParams)}${
      hash ? `#${hash}` : ""
    }`;
  }, [href, utmCampaign, utmContent, utmMedium, utmSource, utmTerm]);

  return (
    <>
      <MuiLink href={hrefMemo} {...other} />
    </>
  );
}
