import { Box, Typography } from '@mui/material';
import { ComponentPropsWithoutRef } from 'react';
import { LearnMoreMenuButton } from '../@navigation/learn-more-menu-button';
import { StyledPageTitle } from './styles';
import { PageTitleProps, PageTitleButtonProps } from './types';
import { Link } from '../@navigation/link';

function PageTitleButton({ menuButtonText, links, href, onClick }: PageTitleButtonProps) {
  if (menuButtonText && links && !href && onClick === undefined) {
    return <LearnMoreMenuButton links={links} buttonText={menuButtonText} />;
  } else if (href) {
    return (
      <Link href={href} onClick={onClick} target="_blank" table={true}>
        {menuButtonText}
      </Link>
    );
  } else {
    return (
      <Link onClick={onClick} table={true}>
        {menuButtonText}
      </Link>
    );
  }
}

function PageTitle({
  title,
  subtitle,
  links,
  menuButtonText,
  titleProps,
  subtitleProps,
  href,
  onClick,
  ...rest
}: PageTitleProps & ComponentPropsWithoutRef<typeof StyledPageTitle>) {
  return (
    <StyledPageTitle {...rest}>
      <Typography variant="h1" className="title" {...titleProps}>
        {title}
      </Typography>
      <Box className="subtitle-container">
        {subtitle && (
          <Typography variant="subtitle1" className="subtitle" {...subtitleProps}>
            {subtitle}
          </Typography>
        )}
        <PageTitleButton
          menuButtonText={menuButtonText}
          links={links}
          href={href}
          onClick={onClick}
        />
      </Box>
    </StyledPageTitle>
  );
}

export default PageTitle;
