import { type FC, type ReactNode } from 'react';
import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';

import { useGetUnreadChannels } from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { getCountNotifications } from 'src/pages/dashboard/notifications/services';

import { notificationCenterKeys } from 'src/pages/dashboard/notifications/queries';
import { formatNotificationCountForTitle } from 'src/pages/dashboard/notifications/utils';

const DEFAULT_TITLE = 'Humand';

type GlobalHelmetTitlePrefixProps = {
  children?: ReactNode;
};

/**
 * Renders a global Helmet with dynamic titleTemplate so that when child routes
 * set <title> via Helmet, the final document title is prefixed with the
 * unread notifications count when > 0, e.g. "(3) Feed | Humand".
 * Pages do not need to add this prefix manually.
 */
export const GlobalHelmetTitlePrefix: FC<GlobalHelmetTitlePrefixProps> = ({
  children,
}) => {
  const { data: notificationsStats } = useQuery(
    notificationCenterKeys.stats(),
    () => getCountNotifications(),
    {
      select: res => res.data,
      refetchOnWindowFocus: false,
    },
  );

  const { data: unreadChannelsCount } = useGetUnreadChannels();

  const count = notificationsStats?.newSinceLastSeen ?? 0;
  const totalCount = count + unreadChannelsCount;
  const displayText = formatNotificationCountForTitle(
    totalCount,
    totalCount > 99,
  );
  const titleTemplate = totalCount > 0 ? `(${displayText}) %s` : '%s';

  return (
    <>
      <Helmet
        titleTemplate={titleTemplate}
        defaultTitle={DEFAULT_TITLE}
      />
      {children}
    </>
  );
};
