import { FC, memo } from 'react';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import { logEvent } from 'src/config/logging';
import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import usePermissions from 'src/hooks/usePermissions';
import {
  invalidateFeedPendingApprovalPostList,
  invalidateFeedScheduledPostList,
  pushFeedListData,
} from 'src/pages/dashboard/feed/queries';
import { createPost } from 'src/services/posts';
import { EventName } from 'src/types/amplitude';
import { PostState } from 'src/types/feed';
import { ApprovalStatus } from 'src/types/groups';
import { Post } from 'src/types/posts';
import { checkAndShowError } from 'src/utils/errorHandlers';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';
import { getPollDeadlineValidationErrorKey } from 'src/utils/poll';

import PostAddForm from './PostAddForm';

const { CREATE_POSTS } = UserPermissions;

export type PostAddProps = {
  onScheduledPostView: () => void;
};

const PostAdd: FC<PostAddProps> = props => {
  const { onScheduledPostView } = props;

  // Loading the group namespace because useInfiniteMembersSearch uses it, remove once we move this to a more general translation file
  const { t } = useLokaliseTranslation(['group']);
  const showGeneralError = useGeneralError();
  const HuGoThemeProvider = useHuGoTheme();
  const { hasAll: userCanPost } = usePermissions([CREATE_POSTS]);

  const handleSuccess = (post: Post) => {
    logEvent(EventName.POST_CREATE, {
      postId: post?.id,
      firstName: post?.user.firstName,
      lastName: post?.user.lastName,
    });
    const isScheduled = post.state === PostState.SCHEDULED;
    const isPending = post.approvalStatus === ApprovalStatus.PENDING;
    const isPosted = post.state === PostState.POSTED;
    if (isPending) {
      invalidateFeedPendingApprovalPostList();
    } else if (isPosted) {
      pushFeedListData(post);
    } else if (isScheduled) {
      invalidateFeedScheduledPostList();
    }
  };

  const handleError = (error: unknown) => {
    checkAndShowError(error, showGeneralError, t, [
      getPollDeadlineValidationErrorKey,
    ]);
  };

  if (!userCanPost) return null;

  return (
    <HuGoThemeProvider>
      <HuCardContainer fullWidth>
        <PostAddForm
          request={createPost}
          onSuccess={handleSuccess}
          onError={handleError}
          onScheduledPostView={onScheduledPostView}
        />
      </HuCardContainer>
    </HuGoThemeProvider>
  );
};

export default memo(PostAdd);
