import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HTMLBody from '@material-hu/components/composed-components/HTMLBody';
import Image from '@material-hu/components/composed-components/Image';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { JourneyTaskDetail } from '../../../types';

const PILL_SPAN_REGEX =
  /<span[^>]*\bdata-variable-token="[^"]*"[^>]*>(?:[^<]|<(?!\/span>)[^>]*>[^<]*<\/span>)*<\/span>/g;
const LABEL_ATTR_REGEX = /\bdata-variable-label="([^"]*)"/;

const stripVariablePills = (html: string): string =>
  html.replace(
    PILL_SPAN_REGEX,
    match => LABEL_ATTR_REGEX.exec(match)?.[1] ?? '',
  );

type TaskBodyProps = {
  task: JourneyTaskDetail | undefined;
  isLoading: boolean;
};

export const TaskBody = ({ task, isLoading }: TaskBodyProps) => {
  const { t } = useLokaliseTranslation('employee_lifecycle');
  const coverImage = task?.task?.coverImage;
  const rawDescription = task?.task?.description;
  const description = rawDescription
    ? stripVariablePills(rawDescription)
    : undefined;

  return (
    <Stack
      sx={{
        borderRadius: 1.5,
        backgroundColor: ({ palette }) => palette.new.background.layout.default,
      }}
    >
      {coverImage && (
        <Image
          sx={{
            maxHeight: 140,
            borderBottomLeftRadius: 0,
            borderBottomRightRadius: 0,
            objectFit: 'cover',
          }}
          src={coverImage?.url || ''}
          loading={isLoading}
        />
      )}

      <Typography
        variant="globalS"
        fontWeight="fontWeightSemiBold"
        sx={{ p: 2 }}
      >
        {t('custom_task_detail.description')}
      </Typography>

      {description && (
        <Stack
          sx={{
            px: 2,
            mx: 2,
            mb: 2,
            maxWidth: '100%',
            borderRadius: 1.5,
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.tertiary,
          }}
        >
          <HTMLBody
            body={description}
            parserOptions={{ video: { controls: true } }}
          />
        </Stack>
      )}
    </Stack>
  );
};
