import React, { ComponentProps } from 'react';
import { Text, as } from 'folds';
import { useTranslation } from 'react-i18next';
import { timeDayMonYear, timeHourMinute, today, yesterday } from '../../utils/time';

export type TimeProps = {
  compact?: boolean;
  ts: number;
};

/**
 * Renders a formatted timestamp using the system locale's hour and date format.
 *
 * Today/yesterday/`compact` show time only; older messages show date + time.
 */
export const Time = as<'span', TimeProps & ComponentProps<typeof Text>>(
  ({ compact, ts, ...props }, ref) => {
    const { t } = useTranslation();
    const formattedTime = timeHourMinute(ts);

    let time = '';
    if (compact) {
      time = formattedTime;
    } else if (today(ts)) {
      time = formattedTime;
    } else if (yesterday(ts)) {
      time = `${t('Room.yesterday')} ${formattedTime}`;
    } else {
      time = `${timeDayMonYear(ts)} ${formattedTime}`;
    }

    return (
      <Text as="time" style={{ flexShrink: 0 }} size="T200" priority="300" {...props} ref={ref}>
        {time}
      </Text>
    );
  }
);
