/* eslint-disable jsx-a11y/click-events-have-key-events */
import { Box, Typography } from '@mui/material';
import dayjs from 'dayjs';
import { useCallback, useMemo } from 'react';
import {
  useLocaleState,
  useNotify,
  useRecordContext,
  useRedirect,
  useResourceContext,
  useTranslate,
  useUpdate
} from 'react-admin';

function NotificationField(props: any): JSX.Element {
  const record = useRecordContext(props);
  const resource = useResourceContext(props);
  const redirect = useRedirect();
  const notify = useNotify();
  const translate = useTranslate();
  const [locale] = useLocaleState();
  const readed = useMemo(
    () => (record?.readed ? dayjs(record?.readed).locale(locale).format('ddd, DD MMM YYYY HH:mm:ss') : false),
    [record?.readed, locale]
  );

  const [update] = useUpdate(
    resource,
    {
      id: record?.id,
      data: {
        ...record,
        readed: dayjs().toISOString()
      }
    },
    {
      onSuccess: () => {
        if (record?.resource) {
          if (record?.resource.startsWith('/')) {
            redirect(record?.resource);
          } else {
            document.location.href = record?.resource;
          }
        }
      },
      onError: () => {
        notify('ra.notification.readed_error', { type: 'warning' });
      }
    }
  );
  const handleUpdate = useCallback(() => update(), [update]);

  return (
    <div onClick={handleUpdate} style={{ cursor: 'pointer' }} role="button" tabIndex={0}>
      <Typography variant="subtitle1">
        <Box fontWeight={'bold'}> {record?.title}</Box>
      </Typography>
      <Typography
        variant="body1"
        sx={{
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          display: '-webkit-box',
          WebkitBoxOrient: 'vertical',
          whiteSpace: 'break-spaces'
        }}
        dangerouslySetInnerHTML={{ __html: record?.content }}
      />
      {readed ? (
        <Typography variant="caption" display="block" sx={{ mt: 1 }} color="textSecondary">
          {translate('ra.notification.readed', { readed })}
        </Typography>
      ) : null}
    </div>
  );
}
export { NotificationField };
