import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { formatPrettyMsLocale, formatToDatetime } from '@blocklet/payment-react';
import { Tooltip, Typography } from '@mui/material';
import prettyMs from 'pretty-ms-i18n';

export default function RelativeTime({ value, ...rest }: { value: string | number }) {
  const { t, locale } = useLocaleContext();
  if (!value) {
    return '-';
  }

  const prettyOption = {
    locale: formatPrettyMsLocale(locale),
    compact: true,
  };

  const valTime = new Date(value).getTime();
  const now = Date.now();

  if (valTime > now) {
    const time = prettyMs(valTime - now, prettyOption);

    return (
      <Tooltip title={formatToDatetime(value, locale)} placement="top-end" enterTouchDelay={0}>
        <Typography component="span" {...rest}>
          {t('common.afterTime', { time })}
        </Typography>
      </Tooltip>
    );
  }

  const time = prettyMs(now - valTime, prettyOption);
  return (
    <Tooltip title={formatToDatetime(value, locale)} placement="top-end" enterTouchDelay={0}>
      <Typography component="span" sx={{ cursor: 'pointer' }} {...rest}>
        {t('common.timeAgo', { time })}
      </Typography>
    </Tooltip>
  );
}
