import {
  CardBody,
  CardGroup,
  Card,
  CardTitle,
  Label,
  Container
} from "reactstrap";
import { getTopicStyleFromTopic } from "../../../lib/getTopicStyle";
import styles from "./PostsCard.module.scss";
import { useRouter } from "next/router";

export function PostsCard({ posts, selectedTopics }) {
  const router = useRouter();

  function postMatchesTopics(post) {
    for (let topic of post.topics) {
      if (selectedTopics.includes(topic)) {
        return true
      }
    }
    return false
  }


  const createPostsDisplay = (postArray) => {
    return (
      <CardGroup className={styles.underline} key={postArray.id}>
        <Label className="d-flex">
          <input
            className={styles.radio}
            type="checkbox"
            name="radio"
            disabled
            checked={postArray.selected}
          />


          <div key={postArray.id} className={styles.postDisplay}>
            <a href={`/discuss/${postArray.id}`}>
              <Label className={styles.threadHeader}>{postArray.title}</Label>
              <br />
              <Label className={`${styles.tag} ${getTopicStyleFromTopic(postArray.topics[0])}`}>
                {postArray.topics[0]}
              </Label>
              <br />
              <Label className={styles.threadDate}>
                Posted {new Date(postArray.created_at).toDateString()} by <a href={postArray.user ? `/users/${postArray.user}` : "#"} className={styles.postAs}>{postArray.post_as}</a>
              </Label>
            </a>
          </div>
        </Label>
      </CardGroup>
    );
  };

  return (
    <Container fluid className="h-100">
      <Card className={styles.cardFormatting}>
        <CardBody className={styles.cardBody}>
          <CardTitle className={styles.underlineTitle}>
            Discussions in Your Community
          </CardTitle>

          <div className={styles.listOfPosts}>
            {posts.map((post, index) => {
              return postMatchesTopics(post) ?
                createPostsDisplay(post) : (false)
            })}
          </div>
        </CardBody>
      </Card>
    </Container>
  );
}