import { Typography } from '@mui/material';
import dayjs from 'dayjs';
import 'dayjs/locale/en';
import 'dayjs/locale/it';
import relativeTime from 'dayjs/plugin/relativeTime';
import { get } from 'lodash';
import { useMemo } from 'react';
import { DateField, DateFieldProps, useLocaleState, useRecordContext } from 'react-admin';

dayjs.extend(relativeTime);

function DateAgoField(props: DateAgoFieldProps): JSX.Element {
  const record = useRecordContext(props);
  const [locale] = useLocaleState();
  const fromNow = useMemo(
    () => dayjs(get(record, props?.source)).locale(locale).fromNow(),
    [record, props?.source, locale]
  );

  return (
    <>
      <DateField record={record} source={props.source} showTime />
      <br />
      <Typography variant="caption" color="textSecondary">
        {fromNow}
      </Typography>
    </>
  );
}

type DateAgoFieldProps = {
  source: string;
} & DateFieldProps;

export { DateAgoField };
export type { DateAgoFieldProps };
