Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 7226 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useEffect, useRef, useState } from 'react'
import { axios } from '../../utils'
import { useHistory, useLocation } from 'react-router-dom'
import { addNotification } from '../../redux/notification/notification.actions'
import { useDispatch, useSelector } from 'react-redux'
import { Col, Container, Row } from 'react-bootstrap'
import styled from 'styled-components'

import QuestionCard from '../../components/my-coach/QuestionCard'
import ConfirmModal from '../../components/modals/ConfirmModal'
import AnswerCard from '../../components/my-coach/AnswerCard'
import AnswerModal from '../../components/my-coach/AnswerModal'

const StyledSection = styled(Col)`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin: auto;
`

const MyCoachViewPage = () => {
  const [question, setQuestion] = useState({})
  const [answers, setAnswers] = useState([])
  const [modalShow, setModalShow] = useState(null)
  const [currentAnswer, setCurrentAnswer] = useState('')
  const addUrl = useRef('')
  const actionUrl = useRef('')
  const labels = useSelector(({ intl }) => intl.labels)
  const dispatch = useDispatch()
  const { pathname } = useLocation()
  const history = useHistory()

  const getQuestion = () => {
    axios
      .get(pathname, {
        headers: {
          'Content-Type': 'application/json',
        },
      })
      .then((response) => {
        const { data, success } = response.data

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Error interno. Por favor, inténtelo de nuevo más tarde.'

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

        addUrl.current = data.link_answers_add
        setQuestion(data)
      })
      .catch((error) => {
        dispatch(
          addNotification({
            style: 'danger',
            msg: 'Error interno. Por favor, inténtelo de nuevo más tarde.',
          })
        )
        throw new Error(error)
      })
  }

  const confirmDelete = () => {
    axios
      .post(actionUrl.current)
      .then((response) => {
        const { data, success } = response.data

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Ha ocurrido un error, por favor intente más tarde.'

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

        closeModal()
        dispatch(addNotification({ style: 'success', msg: data }))
        history.replace('/my-coach')
      })
      .catch((error) => {
        dispatch(
          addNotification({
            style: 'danger',
            msg: 'Ha ocurrido un error, por favor intente más tarde.',
          })
        )
        throw new Error(error)
      })
  }

  const confirmDeleteAnswer = () => {
    axios
      .post(actionUrl.current)
      .then((response) => {
        const { data, success } = response.data

        if (!success) {
          const errorMessage =
            typeof data === 'string'
              ? data
              : 'Ha ocurrido un error, por favor intente más tarde.'

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

        setQuestion((prevQuestion) => ({
          ...prevQuestion,
          comments: data.total_comments,
          answers: data.total_answers,
          reactions: data.total_reactions,
        }))
        closeModal()
      })
      .catch((error) => {
        dispatch(
          addNotification({
            style: 'danger',
            msg: 'Ha ocurrido un error, por favor intente más tarde.',
          })
        )
        throw new Error(error)
      })
  }

  const deleteQuestion = (url) => {
    actionUrl.current = url
    setModalShow('delete')
  }

  const editQuestion = (url) => {
    actionUrl.current = url
    setModalShow('edit')
  }

  const closeModal = () => {
    actionUrl.current = ''
    setModalShow(null)
    setCurrentAnswer('')
  }

  const addAnswer = () => {
    setModalShow('addAnswer')
  }

  const editAnswer = (url, text) => {
    setModalShow('editAnswer')
    actionUrl.current = url
    setCurrentAnswer(text)
  }

  const deleteAnswer = (url) => {
    setModalShow('deleteAnswer')
    actionUrl.current = url
  }

  const onAddAnswer = ({ answers, item }) => {
    setQuestion((prevQuestion) => ({ ...prevQuestion, answers }))
    setAnswers((prevAnswers) => [item, ...prevAnswers])
  }

  const onEditAnswer = ({ description }) => {
    const newAnswers = answers.map((answer) => {
      if (answer.link_edit === actionUrl.current) {
        return { ...answer, text: description }
      }

      return answer
    })

    setAnswers(newAnswers)
  }

  const updateTotalComments = (total) => {
    setQuestion({
      ...question,
      comments: total,
    })
  }

  const updateTotalReactions = (total) => {
    setQuestion({
      ...question,
      reactions: total,
    })
  }

  useEffect(() => {
    getQuestion()
  }, [])

  useEffect(() => {
    if (question.link_answers) {
      axios
        .get(question.link_answers)
        .then((response) => {
          const { data, success } = response.data

          if (!success) {
            const errorMessage =
              typeof data === 'string'
                ? data
                : 'Error interno. Por favor, inténtelo de nuevo más tarde.'

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

          setAnswers(data.items)
        })
        .catch((error) => {
          dispatch(
            addNotification({
              style: 'danger',
              msg: 'Error interno. Por favor, inténtelo de nuevo más tarde.',
            })
          )
          throw new Error(error)
        })
    }
  }, [question])

  return (
    <>
      <Container as="section" className="companies-info">
        <div className="company-title">
          <h1 className="title mx-auto">{labels.my_coach}</h1>
        </div>
        <Row>
          <StyledSection md="8">
            <QuestionCard
              key={question.uuid}
              onEdit={editQuestion}
              onDelete={deleteQuestion}
              onReply={addAnswer}
              {...question}
            />
            {answers.map((answer) => (
              <AnswerCard
                key={answer.unique}
                {...answer}
                onEdit={editAnswer}
                onDelete={deleteAnswer}
                updateComments={updateTotalComments}
                updateReactions={updateTotalReactions}
              />
            ))}
          </StyledSection>
        </Row>
      </Container>
      <AnswerModal
        url={currentAnswer ? actionUrl.current : addUrl.current}
        show={['addAnswer', 'editAnswer'].includes(modalShow)}
        currentAnswer={currentAnswer}
        onClose={closeModal}
        onComplete={currentAnswer ? onEditAnswer : onAddAnswer}
      />
      <ConfirmModal
        show={modalShow === 'deleteAnswer'}
        onClose={closeModal}
        onAccept={confirmDeleteAnswer}
      />
      <ConfirmModal
        show={modalShow === 'delete'}
        onClose={closeModal}
        onAccept={confirmDelete}
      />
    </>
  )
}

export default MyCoachViewPage