import { memo } from 'react';

import { addDays, isBefore } from 'date-fns';
import { type SxProps } from '@material-hu/mui';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import ClockIcon from 'src/icons/Clock';
import {
  formatDistanceToNow,
  getCompletedDateWithTime,
  getCompletedDateWithTimeAndDay,
} from 'src/utils/date';

type TimeDistanceProps = {
  date: Date | null;
  showIcon?: boolean;
  sx?: SxProps;
  typographySx?: SxProps;
  isComment?: boolean;
  showFullDate?: boolean;
};

const TimeDistance = ({
  date,
  showIcon = true,
  sx = {},
  typographySx = {},
  isComment = false,
  showFullDate: showFullDateProp,
}: TimeDistanceProps) => {
  const HugoThemeProvider = useHuGoTheme();
  const { user } = useAuth();

  if (!(date instanceof Date) || isNaN(date.getTime())) return null;

  const showFullDate =
    showFullDateProp ?? isBefore(date, addDays(new Date(), -1));

  const dateText = showFullDate
    ? getCompletedDateWithTime(date, user!)
    : formatDistanceToNow(date, user!, isComment);

  const fullDateText = getCompletedDateWithTimeAndDay(date, user!);

  return (
    <HugoThemeProvider>
      <HuTooltip
        title={fullDateText}
        direction="bottom"
        slotProps={{
          tooltip: {
            sx: {
              maxWidth: 'none !important',
            },
          },
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            mt: 0,
            gap: 0.5,
            ...sx,
          }}
        >
          {showIcon && (
            <ClockIcon
              fontSize="small"
              sx={{ color: 'text.secondary' }}
            />
          )}
          <Typography
            variant="globalXXS"
            fontWeight="fontWeightSemiBold"
            sx={{
              color: theme => theme.palette.new.text.neutral.lighter,
              minWidth: 0,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              ...typographySx,
            }}
          >
            {dateText}
          </Typography>
        </Stack>
      </HuTooltip>
    </HugoThemeProvider>
  );
};

export default memo(TimeDistance);
