import { useLayoutNotificationsState } from '@/components/Layout/Provider';
import { MessageOutlined } from '@ant-design/icons';
import { Avatar, Box, ListItem, ListItemAvatar, ListItemButton, ListItemText, useTheme } from '@mui/material';
import dayjs from 'dayjs';
import { useLocaleState, useNotify, useRedirect, useUpdate } from 'ra-core';
import { useCallback, useMemo } from 'react';

type INotification = {
  id: string;
  readed: number | null;
  resource: string;
  created: string | number | dayjs.Dayjs | Date | null | undefined;
  title: string;
  content: string;
};

type IHeaderNotificationItemProps = {
  selected: boolean;
  notification: INotification;
  onClick: () => void;
  divider?: boolean;
};
function HeaderNotificationItem(props: IHeaderNotificationItemProps) {
  const theme = useTheme();
  const { notification, onClick, selected, divider } = props;
  const { resource } = useLayoutNotificationsState();
  const notify = useNotify();
  const redirect = useRedirect();
  const [update] = useUpdate(
    resource,
    {
      id: notification?.id,
      data: {
        ...notification,
        readed: dayjs().toISOString()
      }
    },
    {
      onSuccess: () => {
        // eslint-disable-next-line no-console
        if (notification?.resource) {
          if (notification?.resource.startsWith('/')) {
            redirect(notification?.resource);
            onClick();
          } else {
            onClick();
            document.location.href = notification?.resource;
          }
        } else {
          onClick();
        }
      },
      //@ts-ignore
      onFailure: () => {
        //@ts-ignore
        notify('resources.notifications.messages.readed.error', 'warning');
      }
    }
  );
  const handleClick = useCallback(() => update(), [update]);
  const [locale] = useLocaleState();
  const ago = useMemo(() => dayjs(notification.created).locale(locale).fromNow(), [notification, locale]);

  return (
    <ListItem disablePadding divider={divider}>
      <ListItemButton selected={selected} onClick={handleClick}>
        <ListItemAvatar>
          <Avatar
            sx={{
              color: 'primary.main',
              bgcolor: 'primary.lighter'
            }}
          >
            <MessageOutlined />
          </Avatar>
        </ListItemAvatar>
        <ListItemText
          sx={{
            overflow: 'hidden',
            wordBreak: 'break-word',
            width: '90%'
          }}
          primary={notification.title}
          secondary={notification.content}
        />
        <Box flexGrow={1} flexShrink={1} minWidth={theme.spacing(2)} />
        <ListItemText
          sx={{
            overflow: 'hidden',
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-word'
          }}
          primary={ago}
          primaryTypographyProps={{ variant: 'caption' }}
        />
      </ListItemButton>
    </ListItem>
  );
}

export { HeaderNotificationItem };

export type { INotification };
