import { Card, CardBody, CardTitle, CardText, Label, React, Container } from "reactstrap";
import styles from "./TopicsCard.module.scss";

/*
 * Prints out the selected {city} of the user, along with a list of the {topics}
 * and corresponding checkboxes. It uses {setTopics} to update the page's topics.
 * Parameters:
 * [+] city         :       the city to display.
 * [+] topics       :       the list of topics to display.
 * [+] setTopics    :       the hook to call and update the topics.
 */
export function TopicsCard({
  city,
  topics,
  selectedTopics,
  setSelectedTopics,
  type
}) {

  const toggleTopic = (topic) => {

    let newSelectedTopics = JSON.parse(JSON.stringify(selectedTopics))
    if (!newSelectedTopics.includes(topic)) {
      newSelectedTopics.push(topic)
    }
    else {
      const index = newSelectedTopics.indexOf(topic);
      if (index > -1) { // only splice array when item is found
        newSelectedTopics.splice(index, 1);
      }
    }
    setSelectedTopics(newSelectedTopics)
  }

  const createTopicOptions = () => {

    return (
      <>
        <CardTitle className={styles.underlineTitle}>
          {type == "posts" ? "Select Discussions to View" : "Select Topics of Interest"}
        </CardTitle>
        <div className={styles.cardSection}>
          {topics.map((topic, index) => (
            <CardText className={styles.underline} key={index}>
              <Label className={styles.label + " d-flex justify-content-between"}>
                {topic}
                <input
                  className={styles.radio}
                  type="checkbox"
                  name="radio"
                  onChange={(e) => { toggleTopic(topic) }}
                  checked={selectedTopics.includes(topic)}
                />

              </Label>
            </CardText>
          ))}
        </div>
      </>
    );
  };


  return (
    <Container fluid className="h-100">
      <Card className={styles.cardFormatting}>
        <CardBody>
          <CardTitle className={styles.underlineTitle}>Your Community</CardTitle>
          <CardTitle className={styles.citySpacing}>{city}</CardTitle>
          <div className={styles.disclaimer}>Currently only showing {type} from Miami</div>
          {createTopicOptions()}
        </CardBody>
      </Card>
    </Container>
  );
}