import { FC, useState } from 'react';
import { useMutation } from 'react-query';

import { useModal } from '@material-hu/hooks/useModal';

import * as HuPosts from '@material-hu/components/composed-components/posts';
import HuDialog from '@material-hu/components/design-system/Dialog';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import { useAuth } from 'src/contexts/JWTContext';
import { deletePost, editPost } from 'src/services/events';
import { Event, EventPostType } from 'src/types/events';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import { useIsEventsManager, useIsEventCreator } from '../utils';

import { EventPostCreate } from './EventPostCreate';

type Props = {
  event: Event;
  post: EventPostType;
  refetchPosts: Function;
};

export const EventPost: FC<Props> = ({ event, post, refetchPosts }) => {
  const { t } = useLokaliseTranslation('events');
  const { enqueueSnackbar } = useHuSnackbar();
  const { user } = useAuth();
  const isEventsManager = useIsEventsManager();
  const isEventsCreator = useIsEventCreator(event);
  const isPostCreator = post.user.id === user.id;

  const [isEditing, setIsEditing] = useState(false);

  const editPostMutation = useMutation(
    (data: Partial<EventPostType>) => {
      const attachments = [...data.media, ...data.files].map(q => ({
        ...q.attachment,
        url: q.attachment.url.split('?')[0],
      }));

      return editPost(event.id, post.id, { ...data, attachments });
    },
    {
      onSuccess: () => {
        setIsEditing(false);
        refetchPosts();
        enqueueSnackbar({ title: t('POST_EDITED'), variant: 'success' });
      },
    },
  );

  const deletePostMutation = useMutation(() => deletePost(event.id, post.id), {
    onSuccess: () => {
      refetchPosts();
      enqueueSnackbar({ title: t('POST_DELETED'), variant: 'success' }); // PREGUNTA: hay que mostarlo?
    },
  });

  const deletePostModal = useModal(() => (
    <HuDialog
      title={t('DELETE_POST_SURE')}
      textBody={t('DELETE_POST_SURE_DESCRIPTION')}
      onClose={deletePostModal.closeModal}
      primaryButtonProps={{
        children: t('ELIMINATE'),
        onClick: () =>
          deletePostMutation.mutate(null, {
            onSettled: deletePostModal.closeModal,
          }),
        loading: deletePostMutation.isLoading,
      }}
      secondaryButtonProps={{
        children: t('CANCEL'),
        onClick: deletePostModal.closeModal,
        loading: deletePostMutation.isLoading,
      }}
    />
  ));

  const onEdit = isPostCreator && (() => setIsEditing(true));
  const onDelete =
    (isEventsManager || isEventsCreator || isPostCreator) &&
    (() => deletePostModal.showModal());

  if (isEditing) {
    return (
      <EventPostCreate
        handlePost={newPost => editPostMutation.mutateAsync(newPost)}
        existingPost={post}
        onCancel={() => setIsEditing(false)}
        sx={{ my: 4 }}
      />
    );
  }

  return (
    <>
      {deletePostModal.modal}
      <HuPosts.Post
        sx={{ mb: 2 }}
        key={post.id}
        fullName={getFullName(post.user)}
        profilePicture={post.user.profilePicture}
        publicationDatetime={post.publicationDatetime}
        body={post.body}
        media={post.media}
        files={post.files}
        actions={{
          onDelete,
          onEdit,
        }}
      />
    </>
  );
};
