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

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

import { type HighlightedSpan } from 'src/pages/dashboard/Conversations/types';
import {
  getUserFullNameFromId,
  separateTextParts,
  splitTextBySearchQuery,
} from 'src/pages/dashboard/Conversations/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { profileRoutes } from '../../../../profile/routes';

type Props = TypographyProps & {
  children?: string;
  linkProps?: LinkProps;
  disableLink?: boolean;
  highlightQuery?: string;
  highlightedSpans?: HighlightedSpan[];
};

const highlightText = (
  text: string,
  query: string,
  key: string,
  bgColor: string,
  textColor: string,
): React.ReactNode => {
  if (!query) return text;

  const { parts } = splitTextBySearchQuery(text, query);

  return parts.map((part, i) =>
    i % 2 === 1 ? (
      <Typography
        component="mark"
        key={`${key}-highlight-${i}`}
        sx={{
          backgroundColor: bgColor,
          color: textColor,
        }}
      >
        {part}
      </Typography>
    ) : (
      part
    ),
  );
};

const TypographyTagAndLinkSensitive: FC<PropsWithChildren<Props>> = ({
  children = '',
  linkProps = {},
  disableLink = false,
  highlightQuery = '',
  highlightedSpans = [],

  ...typographyProps
}) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation('chat');

  const parts = separateTextParts(children);

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

      if (disableLink) {
        return (
          <Typography
            key={`url-disabled-${index}`}
            {...typographyProps}
          >
            {part.content}
          </Typography>
        );
      }

      return (
        <Link
          key={`url-link-${index}`}
          href={href}
          target="_blank"
          rel="noopener noreferrer"
          sx={{
            /** TODO: cambiar esto cuando se encuentre en el ds */
            color: theme.palette.newBase?.brand[500],
            textDecoration: 'none',
            fontWeight: 'fontWeightSemiBold',
            '&:hover': {
              textDecoration: 'underline',
            },
          }}
          {...linkProps}
        >
          {part.content}
        </Link>
      );
    }

    if (part.type === 'mention' && part.userId) {
      if (part.isAll) {
        return (
          <Typography
            key={`mention-link-all-${index}`}
            {...typographyProps}
          >
            <Typography
              {...typographyProps}
              component="span"
            >
              @
            </Typography>
            <Typography
              component="span"
              sx={{
                /** TODO: cambiar esto cuando se encuentre en el ds */
                color: disableLink
                  ? 'inherit'
                  : theme.palette.newBase?.brand[500],
                fontWeight: disableLink ? 'inherit' : 'fontWeightSemiBold',
                fontSize: 'inherit',
              }}
            >
              all
            </Typography>
          </Typography>
        );
      }
      const fullName = getUserFullNameFromId(part.userId, highlightedSpans);
      if (!fullName) {
        return (
          <Typography
            key={`mention-unknown-${index}-${part.userId}`}
            {...typographyProps}
            component="span"
          >
            {t('messages.mention_not_available')}
          </Typography>
        );
      }

      if (disableLink) {
        return (
          <Typography
            key={`mention-disabled-${index}-${part.userId}`}
            {...typographyProps}
          >
            @{fullName}
          </Typography>
        );
      }

      return (
        <Typography
          key={`mention-link-${index}-${part.userId}`}
          {...typographyProps}
        >
          <Typography
            {...typographyProps}
            component="span"
          >
            @
          </Typography>
          <Link
            href={profileRoutes.profile(part.userId)}
            sx={{
              /** TODO: cambiar esto cuando se encuentre en el ds */
              color: theme.palette.newBase?.brand[500],
              textDecoration: 'none',
              fontWeight: 'fontWeightSemiBold',
            }}
          >
            {fullName}
          </Link>
        </Typography>
      );
    }

    return (
      <React.Fragment key={`text-${index}`}>
        {highlightText(
          part.content,
          highlightQuery,
          `text-${index}`,
          theme.palette.newBase?.brand[500] || '',
          theme.palette.newBase?.white || '',
        )}
      </React.Fragment>
    );
  });

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

export default TypographyTagAndLinkSensitive;
