import { Container, Row, Col } from "reactstrap"
import { useState, useEffect } from "react";
import styles from "./[id].module.scss";
import { getTopicStyleFromTopic } from "../../lib/getTopicStyle";
import axios from "axios";
import { useRouter } from 'next/router';
import { getUser } from "../../../lib/requests";

function Post({ post }) {
  const router = useRouter()

  const [user, setUser] = useState(null)
  const [replyClicked, setReplyClicked] = useState(false)
  const [postState, setPostState] = useState({
    user: "",
    description: ""
  });

  useEffect(async () => {
    setUser(await getUser())
  }, [])

  function handleReplyButtonClick() {
    setReplyClicked(true);
  }

  function handleDiscardButtonClick() {
    setReplyClicked(false);
    setPostState({ description: "" })
  }

  const onSubmit = () => {
    axios({
      url: "/posts/" + post.id + "/comments/",
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      data: { reply_as: postState.user, text: postState.description }
    }).then(() => {
      router.reload()
    }).catch(error => console.log(error))
  }
  console.log(post)

  return (
    <>
      <Container fluid>
        <Row>
          <Col md={12} lg={7} className="g-2">
            <div className={styles.card}>
              <Row className={styles.cardTitle}>
                <Col xs={7} className={`${styles.title}`}>{post.title}</Col>
                <Col xs={5} className={styles.postedBy}>Posted By <span className={styles.postedBySpan} onClick={() => { router.push(`/users/${post.user.id}`) }}>{post.post_as}</span></Col>
              </Row>
              <div className={styles.cardBody}>
                <Row className={"mb-1"}>
                  <Col xs={6} >
                    <div className={`${styles.tag} ${getTopicStyleFromTopic(post.topics[0])}`}>
                      {post.topics[0]}
                    </div>
                  </Col>
                  <Col xs={6}>
                    <div className={styles.created}>
                      {new Date(post.created_at).toDateString()}
                    </div>
                  </Col>
                </Row>
                <div className={styles.textarea} readOnly>
                  {post.text}
                </div>
                <Row className="ms-auto">
                  <Col>
                    <button className={styles.discardButton} onClick={() => { router.push("/discuss") }}>
                      Back
                    </button>
                  </Col>
                  <Col>
                    <button id="reply" className={styles.replyButton} onClick={handleReplyButtonClick}>
                      Reply
                    </button>
                  </Col>
                </Row>
                {(() => {
                  if (replyClicked) {
                    return (
                      <>
                        {user == null ?
                          <><input placeholder="Reply as..." className={styles.nameBox} onChange={(event) => setPostState({ ...postState, user: event.target.value })}></input></> :
                          <><input type="text" value={`${user.first_name} ${user.last_name}`} className={styles.nameBox} readOnly></input></>
                        }
                        <textarea placeholder="Type here..." className={styles.replyBox} onChange={(event) => setPostState({ ...postState, description: event.target.value })}></textarea>
                        <div id="container">
                          <button className={styles.replyButton} onClick={onSubmit}>Post</button>
                          <button className={styles.discardButton} onClick={handleDiscardButtonClick} >Discard</button>
                        </div>
                      </>
                    )
                  } else {
                    return (undefined)
                  }
                })()}
              </div>
            </div>
          </Col>
          <Col md={12} lg={5} className="g-2">
            <div className={styles.card}>
              <Row className={styles.cardTitle}>
                <span className={styles.replies}>Replies</span>
              </Row>
              <div className={`${styles.cardBody} ${styles.comments}`}>
                {(() => {
                  if (post.comments.length >= 1) {
                    return (
                      <>
                        {post.comments.map((comment) => {
                          return (
                            <div key={comment.id} className={styles.comment}>
                              <div className={styles.commentUser}>
                                {comment.reply_as}
                              </div>
                              <div className={styles.commentText}>
                                {comment.text}
                              </div>
                            </div>
                          )
                        })}
                      </>
                    )
                  } else {
                    return (
                      <h1 className={styles.noComments}>No comments</h1>
                    )
                  }
                })()}
              </div>
            </div>
          </Col>
        </Row>
      </Container>
    </>
  )
}

export async function getServerSideProps(context) {
  let res = await axios({
    url: `/posts/${context.query.id}`,
  })
  if (res.status == 200) {
    return {
      props: { post: res.data },
    }
  } else {
    return {
      props: undefined,
    }
  }

}

export default Post
//post
