import React, { useState } from 'react'

import ReactButton from './reactButton'
import Modal from './modal'
import Link from 'next/link'

import styles from './comments.module.css'

function CommentInput({ onSubmit, onCancel }) {
  const [val, setVal] = useState('')
  return (
    <div className={styles.commentAreaContainer}>
      <textarea
        autoFocus
        value={val}
        onChange={(e) => {
          setVal(e.target.value)
        }}
      />
      <div className={'actions'}>
        <span
          onClick={() => {
            onSubmit(val)
          }}
        >
          Küldés
        </span>
        <span
          onClick={() => {
            onCancel()
          }}
        >
          Bezárás
        </span>
      </div>
    </div>
  )
}

function Comment({ comment, index, onComment, onDelete, onReact, uid }) {
  const [displayed, setDisplayed] = useState(true)
  const [commenting, setCommenting] = useState(false)
  const { content, subComments, date, user, reacts, admin } = comment
  const dateObj = new Date(date)
  const own = uid === user

  const commentStyle = admin
    ? styles.adminComment
    : own
    ? styles.ownComment
    : ''

  return (
    <div className={styles.comment}>
      <div className={`${styles.commentData} ${commentStyle}`}>
        <div className={styles.commentHeader}>
          <div className={styles.userContainer}>
            <div
              className={styles.showHide}
              onClick={() => {
                setDisplayed(!displayed)
              }}
            >
              {displayed ? '[-]' : '[+]'}
            </div>
            <Link
              href={`/chat?user=${user}`}
              title={`Chat #${user}-el`}
              className={'userId'}>
              User #{user}

            </Link>
          </div>
          <div className={styles.commentDate} title={dateObj.toLocaleString()}>
            @
            {dateObj.getDate() !== new Date().getDate()
              ? dateObj.toLocaleDateString()
              : dateObj.toLocaleTimeString()}
          </div>
        </div>
        <div className={`${!displayed ? styles.hidden : ''}`}>
          <div className={styles.commentText}>{content}</div>
          <div className={'actions'}>
            <span
              className={styles.reply_bttn}
              onClick={() => {
                setCommenting(true)
              }}
            >
              Válasz...
            </span>
            {own && (
              <span
                onClick={() => {
                  onDelete([index])
                }}
              >
                Törlés
              </span>
            )}
            <ReactButton
              onClick={(reaction, isDelete) => {
                onReact([index], reaction, isDelete)
              }}
              uid={uid}
              existingReacts={reacts}
            />
          </div>
          {commenting && (
            <CommentInput
              onCancel={() => {
                setCommenting(false)
              }}
              onSubmit={(e) => {
                onComment([index], e)
                setCommenting(false)
              }}
            />
          )}
        </div>
      </div>
      <div className={`${!displayed && styles.hidden}`}>
        {subComments &&
          subComments.map((sc, i) => {
            return (
              <Comment
                comment={sc}
                onReact={(path, reaction, isDelete) => {
                  onReact([...path, index], reaction, isDelete)
                }}
                onDelete={(path) => {
                  onDelete([...path, index])
                }}
                onComment={(path, content) => {
                  onComment([...path, index], content)
                }}
                index={i}
                key={i}
                uid={uid}
              />
            )
          })}
      </div>
    </div>
  );
}

function countComments(comments) {
  return comments.reduce((acc, comment) => {
    if (comment.subComments) {
      acc += countComments(comment.subComments) + 1
    } else {
      acc += 1
    }
    return acc
  }, 0)
}

export default function Comments({
  comments,
  onComment,
  onDelete,
  onReact,
  uid,
}) {
  const [addingNewComment, setAddingNewComment] = useState(false)
  const [commentsShowing, setCommentsShowing] = useState(false)
  const commentCount = comments ? countComments(comments) : 0

  return (
    <div>
      {commentsShowing ? (
        <Modal
          closeClick={() => {
            setCommentsShowing(false)
          }}
        >
          {comments && comments.length > 0
            ? comments.map((comment, i) => {
                return (
                  <Comment
                    onReact={onReact}
                    onComment={onComment}
                    onDelete={onDelete}
                    comment={comment}
                    index={i}
                    key={i}
                    uid={uid}
                  />
                )
              })
            : null}
          {commentCount !== 0 ? (
            <div className={'actions'}>
              <span
                className={styles.comment_bttn}
                onClick={() => {
                  setAddingNewComment(true)
                }}
              >
                Új komment
              </span>
            </div>
          ) : null}
          {addingNewComment ? (
            <CommentInput
              onSubmit={(e) => {
                if (!e) {
                  alert('Írj be valamit a szövegdobozba, hogy kommentelhess!')
                  return
                }
                setAddingNewComment(false)
                onComment([], e)
              }}
              onCancel={() => {
                setAddingNewComment(false)
                if (commentCount === 0) {
                  setCommentsShowing(false)
                }
              }}
            />
          ) : null}
        </Modal>
      ) : null}
      <div className={'actions'}>
        <span
          onClick={() => {
            setCommentsShowing(true)
            if (commentCount === 0) {
              setAddingNewComment(true)
            }
          }}
          className={styles.comment_bttn}
        >
          {commentCount === 0
            ? 'Új komment'
            : `Kommentek mutatása (${commentCount})`}
        </span>
      </div>
    </div>
  )
}
