import {useMemo} from 'react';
import {useTranslation} from 'react-i18next';
import {Alert, Typography} from '@components';
import {getVariantShape} from '@components/_HuGo/Alert/styles';
import {useTheme} from '@shared/theme';

interface Props {
  minimumTimeFraction?: Nullable<number>;
}

function FractionHoursMessage({minimumTimeFraction}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {textColor} = getVariantShape('error', theme);

  const valueText = useMemo(() => {
    if (minimumTimeFraction == null) {
      return '';
    }

    return String(minimumTimeFraction);
  }, [minimumTimeFraction]);

  const description = useMemo(() => {
    return t('time_off.time_fraction_error_description', {value: valueText});
  }, [t, valueText]);

  const boldText = useMemo(() => {
    if (!valueText) {
      return '';
    }

    const escapedValue = valueText.replaceAll(
      /[.*+?^${}()|[\]\\]/g,
      String.raw`\$&`,
    );
    const match = new RegExp(String.raw`\b${escapedValue}\s+\S+`).exec(
      description,
    );

    return match?.[0] ?? valueText;
  }, [description, valueText]);

  const descriptionNode = useMemo(() => {
    if (!valueText || !boldText) {
      return (
        <Typography variant="xs" color={textColor}>
          {description}
        </Typography>
      );
    }

    const valueIndex = description.indexOf(boldText);

    if (valueIndex === -1) {
      return (
        <Typography variant="xs" color={textColor}>
          {description}
        </Typography>
      );
    }

    const beforeValue = description.slice(0, valueIndex);
    const afterValue = description.slice(valueIndex + boldText.length);

    return (
      <Typography variant="xs" color={textColor}>
        {beforeValue}
        <Typography variant="xs" weight="semiBold" color={textColor}>
          {boldText}
        </Typography>
        {afterValue}
      </Typography>
    );
  }, [boldText, description, textColor, valueText]);

  return (
    <Alert
      title={t('time_off.time_fraction_error_title')}
      variant="error"
      description={descriptionNode}
    />
  );
}

export default FractionHoursMessage;
