Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 2891 | Rev 3002 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Box, Typography } from '@mui/material'
import { ChatOutlined, Edit } from '@mui/icons-material'

import { axios } from '@utils'
import { withReactions } from '@hocs'
import { addNotification } from '@store/notification/notification.actions'

import Widget from '@components/UI/Widget'
import Button from '@components/UI/buttons/Buttons'
import CommentForm from '@components/dashboard/linkedin/comments/comment-form'
import CommentsList from '@components/dashboard/linkedin/comments/comment-list'
import FeedDescription from '@components/dashboard/feed/feed-description'
import Options from '@components/UI/Option'

const AnswerCard = ({
  time_elapsed = '',
  user_image = '',
  user_url = '',
  user_name = '',
  text = '',
  reaction = '',
  total_comments = 0,
  total_reactions = 0,
  comments: defaultComments = [],
  link_edit = '',
  link_delete = '',
  link_reaction_delete = '',
  link_save_reaction = '',
  link_add_comment = '',
  onEdit = () => {},
  onDelete = () => {},
  updateComments = () => {},
  updateReactions = () => {}
}) => {
  const [comments, setComments] = useState(defaultComments)
  const [totalComments, setTotalComments] = useState(total_comments)
  const [totalReactions, setTotalReactions] = useState(total_reactions)
  const [showComments, setShowComments] = useState(false)
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()

  const addComment = (comment) => {
    const formData = new FormData()
    formData.append('comment', comment)

    axios
      .post(link_add_comment, formData)
      .then((response) => {
        const { success, data } = response.data

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Error interno. Intente más tarde.'
          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
          return
        }

        setComments([...comments, data.item])
        updateComments(data.total_comments_question)
        setTotalComments(data.total_comments_answer)
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
  }

  const deleteComment = (commentUnique, deleteCommentUrl) => {
    axios
      .post(deleteCommentUrl)
      .then((response) => {
        const { success, data } = response.data

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Error interno. Intente más tarde.'

          dispatch(addNotification({ style: 'danger', msg: errorMessage }))
          return
        }

        const newComments = comments.filter(
          ({ unique }) => unique !== commentUnique
        )

        dispatch(addNotification({ style: 'success', msg: data.message }))

        setComments(newComments)
        updateComments(data.total_comments_question)
        setTotalComments(data.total_comments_answer)
      })
      .catch((err) => {
        dispatch(addNotification({ style: 'danger', msg: err.message }))
      })
  }

  const ReactionsButton = withReactions(Button)

  return (
    <>
      <Widget>
        <Widget.Header
          avatar={user_image}
          title={user_name}
          subheader={time_elapsed}
          renderAction={() => (
            <Options>
              {link_delete && (
                <Options.Item onClick={() => onDelete(link_delete)}>
                  Borrar
                </Options.Item>
              )}
            </Options>
          )}
        />

        <Widget.Body>
          <FeedDescription description={text} />

          <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
            <Typography variant='overline'>{`${totalReactions} ${labels.reactions}`}</Typography>
            <Typography variant='overline'>{`${totalComments} ${labels.comments}`}</Typography>
          </Box>
        </Widget.Body>

        <Widget.Actions>
          {link_save_reaction && (
            <ReactionsButton
              currentReactionType={reaction}
              saveUrl={link_save_reaction}
              deleteUrl={link_reaction_delete}
              onReaction={({
                total_reactions_answer,
                total_reactions_question
              }) => {
                setTotalReactions(total_reactions_answer)
                updateReactions(total_reactions_question)
              }}
            />
          )}
          {link_add_comment && (
            <Button onClick={() => setShowComments(!showComments)}>
              <ChatOutlined />
              {labels.comment}
            </Button>
          )}
          {link_edit && (
            <Button onClick={() => onEdit(link_edit, text)}>
              <Edit />
              {labels.edit}
            </Button>
          )}
        </Widget.Actions>

        <Box sx={{ padding: 0.5, display: showComments ? 'block' : 'none' }}>
          <CommentForm onSubmit={addComment} />
          <CommentsList comments={comments} onDelete={deleteComment} />
        </Box>
      </Widget>
    </>
  )
}

export default AnswerCard