import { useNavigate } from 'react-router-dom';

import { useTheme } from '@material-hu/mui/styles';

import TaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';
import { type HeaderMainAction } from '@material-hu/components/design-system/Header/types';

import { logEvent } from 'src/config/logging';
import useFormatDate from 'src/hooks/useFormatDate';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useArticleId } from '../../hooks/useArticleId';
import { useArticleNavigation } from '../../hooks/useArticleNavigation';
import { huLibrariesRoutes } from '../../routes';
import { type Article } from '../../types';
import { getArticleAvatarProps } from '../../utils';

type ArticleHeaderProps = { article: Article };

export const ArticleHeader = ({ article }: ArticleHeaderProps) => {
  const { t } = useLokaliseTranslation('libraries');
  const navigate = useNavigate();
  const theme = useTheme();
  const { formatDate } = useFormatDate();
  const { navigateBack } = useArticleNavigation();
  const { rootId, childId } = useArticleId();

  const isEditor = article.isEditor ?? false;

  const showLastUpdatedDescription =
    isEditor && article.lastModifiedUser && article.updatedAt;

  const handleEdit = () => {
    if (!rootId) return;
    logEvent(EventName.LIBRARY_CONTENT_EDIT_CLICK, {
      libraryId: article.id,
      parentId: article.parentId,
      title: article.title,
    });
    navigate(huLibrariesRoutes.edit(rootId, childId));
  };

  const mainActions: HeaderMainAction[] = [
    {
      key: 'edit',
      children: t('general:edit'),
      variant: 'contained',
      onClick: handleEdit,
    },
  ];

  const articleAvatar = getArticleAvatarProps(article, theme);

  const lastUpdatedText = t('article.header.last_updated', {
    day: formatDate(article.updatedAt ?? '', 'd'),
    month: formatDate(article.updatedAt ?? '', 'MMMM'),
    year: formatDate(article.updatedAt ?? '', 'yyyy'),
  });

  return (
    <TaskFocusHeader
      title={article?.title || ''}
      onBack={navigateBack}
      avatar={articleAvatar}
      slotProps={{
        root: {
          sx: {
            '& .MuiStack-root:first-of-type': { maxWidth: '40vw' },
            position: 'sticky',
            top: 0,
            zIndex: 99,
          },
        },
        title: {
          variant: 'S',
          overflow: 'tooltip',
          withEllipsis: true,
          description: showLastUpdatedDescription ? lastUpdatedText : undefined,
        },
      }}
      mainActions={isEditor ? mainActions : undefined}
    />
  );
};
