Proyectos de Subversion LeadersLinked - SPA

Rev

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

import React, { useState } from 'react'
import Button from '../UI/buttons/Buttons'

import { addNotification } from '../../redux/notification/notification.actions'
import { useDispatch, useSelector } from 'react-redux'
import EditIcon from '@mui/icons-material/Edit'
import DeleteIcon from '@mui/icons-material/Delete'
import ChatOutlinedIcon from '@mui/icons-material/ChatOutlined'
import styled from 'styled-components'

import { QuestionStats } from './QuestionCard'
import WidgetWrapper from '../widgets/WidgetLayout'
import CommentForm from '../dashboard/linkedin/comments/comment-form'
import CommentsList from '../dashboard/linkedin/comments/comment-list'
import { withReactions } from '@hocs'
import { Typography } from '@mui/material'
import { axios, parse } from '@utils'

const StyledForm = styled(CommentForm)`
  border: 1px solid lightgray;
  background-color: #fff;
  border-radius: 30px;
  padding: 5px;
  padding-left: 1rem;
  flex: 1;
  cursor: pointer;

  &:hover {
    background-color: rgba(0, 0, 0, 0.08);
  }
`

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 (
    <>
      <WidgetWrapper>
        <WidgetWrapper.Header image={user_image} title={user_name}>
          <QuestionStats>
            <span>{`${labels.published} ${time_elapsed}`}</span>
            <span>{`${totalReactions} ${labels.reactions}`}</span>
            <span>{`${totalComments} ${labels.comments}`}</span>
          </QuestionStats>
        </WidgetWrapper.Header>

        <WidgetWrapper.Body>
          <Typography>{parse(text)}</Typography>
        </WidgetWrapper.Body>

        <WidgetWrapper.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)}>
              <ChatOutlinedIcon />
              {labels.comment}
            </button>
          )}
          {link_edit && (
            <button onClick={() => onEdit(link_edit, text)}>
              <EditIcon />
              {labels.edit}
            </button>
          )}
          {link_delete && (
            <button onClick={() => onDelete(link_delete)}>
              <DeleteIcon />
              {labels.delete}
            </button>
          )}
        </WidgetWrapper.Actions>

        <div className='px-1 pb-1'>
          <StyledForm image={user_image} onSubmit={addComment} />
          {showComments && (
            <CommentsList comments={comments} onDelete={deleteComment} />
          )}
        </div>
      </WidgetWrapper>
    </>
  )
}

export default AnswerCard