import { type FC, Fragment, type PropsWithChildren } from 'react';

import Link, { type LinkProps } from '@material-hu/mui/Link';
import Typography, { type TypographyProps } from '@material-hu/mui/Typography';

import { urlRegex } from '../constants';

type Props = TypographyProps & {
  linkProps?: LinkProps;
};

const TypographyLinkSensitive: FC<PropsWithChildren<Props>> = ({
  children,
  linkProps = {},
  ...typographyProps
}) => {
  if (typeof children !== 'string') {
    return <Typography {...typographyProps}>{children}</Typography>;
  }

  // Split the text into parts, keeping the URLs in the result array
  const parts = children.split(urlRegex);

  const content = parts.map((part, index) => {
    if (urlRegex.test(part)) {
      const href = part.startsWith('www.') ? `http://${part}` : part;

      return (
        <Link
          key={index}
          href={href}
          target="_blank"
          rel="noopener noreferrer"
          {...linkProps}
        >
          {part}
        </Link>
      );
    }

    // Non-URL text segment
    return <Fragment key={index}>{part}</Fragment>;
  });

  return <Typography {...typographyProps}>{content}</Typography>;
};

export default TypographyLinkSensitive;
