import { FC, memo } from 'react';

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

import { logEvent } from 'src/config/logging';
import useCommunityFeature from 'src/hooks/useCommunityFeature';
import useGeneralError from 'src/hooks/useGeneralError';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { createGroupPost } from 'src/services/groups';
import { EventName } from 'src/types/amplitude';
import { CommunityFeature } from 'src/types/communityFeatures';
import { ApprovalStatus, GroupPost, GroupPostStates } from 'src/types/groups';

import { PostData } from 'src/types/posts';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import { postCreated } from '../../feed/queries';
import { useGroupMember } from '../GroupMemberContext';
import {
  invalidateGroupPendingApprovalPostList,
  invalidateGroupScheduledPostList,
  pushGroupFeedListData,
} from '../queries';

import GroupPostAddForm from './GroupPostAddForm';

type GroupPostAddProps = {
  onScheduledPostView: () => void;
};

const GroupPostAdd: FC<GroupPostAddProps> = props => {
  const { onScheduledPostView } = props;
  const { id } = useRequiredParams(['id']);

  const { t } = useTranslation(['group']);
  const showGeneralError = useGeneralError();

  const { userCanPost } = useGroupMember();

  const createPostForGroup = (groupId: string) => (data: PostData) =>
    createGroupPost(groupId, data);

  const canViewGroupPostsInFeed = useCommunityFeature(
    CommunityFeature.VIEW_GROUP_POSTS_IN_FEED,
  );

  const handleSuccess = (post: GroupPost) => {
    const isScheduled = post.state === GroupPostStates.SCHEDULED;
    const isPending = post.approvalStatus === ApprovalStatus.PENDING;
    const isPosted = post.state === GroupPostStates.POSTED;
    if (isPending) {
      invalidateGroupPendingApprovalPostList(post.groupId);
    } else if (isPosted) {
      if (canViewGroupPostsInFeed) {
        postCreated();
      }
      pushGroupFeedListData(post, id);
    } else if (isScheduled) {
      invalidateGroupScheduledPostList(id);
    }

    const pollId = post?.poll?.id;

    const commonParams = { groupId: Number(id), postId: post?.id };

    if (pollId) {
      logEvent(EventName.GROUPS_POST_POLL_CREATED, {
        ...commonParams,
        pollId,
        isScheduled,
      });
    }

    logEvent(EventName.GROUPS_POST_CREATED, {
      ...commonParams,
      isScheduled,
    });

    post.taggedUserIds?.forEach(userId =>
      logEvent(EventName.GROUPS_POST_MENTIONED, {
        ...commonParams,
        userId,
      }),
    );
  };

  const handleError = (error: unknown) =>
    showGeneralError(error, t('post:create_post_error'));

  if (!userCanPost) return null;

  return (
    <HuCardContainer fullWidth>
      <GroupPostAddForm
        request={createPostForGroup(id)}
        onSuccess={handleSuccess}
        onError={handleError}
        onScheduledPostView={onScheduledPostView}
        isGroups
      />
    </HuCardContainer>
  );
};

export default memo(GroupPostAdd);
