import { FC } from 'react';

import { IconCalendarClock } from '@material-hu/icons/tabler';

import { useAuth } from 'src/contexts/JWTContext';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { getFormatedDateTime } from 'src/utils/date';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import AlertAccordion from 'src/components/pendingApprovals/AlertAccordion';

import useGroupScheduledPostsQuery from '../../feed/components/schedule/useGroupScheduledPostsQuery';
import { useGroupMember } from '../GroupMemberContext';

type GroupScheduledPostsAlertProps = {
  onShowScheduledPosts: () => void;
};

const GroupScheduledPostsAlert: FC<GroupScheduledPostsAlertProps> = props => {
  const { onShowScheduledPosts } = props;
  const { user } = useAuth();
  const { userCanSeePosts, isGroupArchived } = useGroupMember();
  const { t } = useTranslation(['group']);
  const { id: groupId } = useRequiredParams(['id']);

  const { data: scheduledPosts, isLoading } =
    useGroupScheduledPostsQuery(groupId);

  const count = scheduledPosts?.pages?.[0]?.data?.count || 0;
  const nextPublicationDatetime =
    scheduledPosts?.pages?.[0]?.data?.items?.[0]?.publicationDatetime || '';

  if (!userCanSeePosts || isLoading || !count || isGroupArchived) {
    return null;
  }

  return (
    <AlertAccordion
      Icon={IconCalendarClock}
      title={t('post:schedule_amount', { count })}
      description={t('post:next_scheduled_post', {
        date: getFormatedDateTime(nextPublicationDatetime, user ?? undefined),
      })}
      buttonTitle={t('post:see_posts')}
      onClick={onShowScheduledPosts}
    />
  );
};

export default GroupScheduledPostsAlert;
