import Paper from "@mui/material/Paper";
import { useEffect, useState } from "react";
import Box from "@mui/material/Box";
import { Button, Grid,  IconButton, Typography } from "@mui/material";
import HelpIcon from "@mui/icons-material/Help";
import CancelIcon from "@mui/icons-material/Cancel";
import { useHistory } from "react-router";
import { fetchSigns } from "../helpers/signs";
import { getNextEmail, postAnswer } from "../helpers/gameruns";
import ReactHtmlParser from "react-html-parser";

let initVal = {
  subject: "",
  sender: "",
  body: "",
  sign: [],
};

// Play page handles rendering gamerun email  and posting answers
export default function PlayPage() {
  // msg containing if answer was correct
  const [msg, setMsg] = useState("");
  const [currentEmail, setCurrentEmail] = useState(initVal);
  // all signs
  const [signs, setSigns] = useState([]);
  // true if help window is opened, otherwise false
  const [helpWindowOpened, setHelpWindowOpened] = useState(false);
  // answered - true if player has answered to current email, otherwise false,
  // answer - player's answer ( true = phishing email, false - legitimate email )
  const [answer, setAnswer] = useState({ answered: false, answer: false });
  const history = useHistory();
  // order of the current email in gamerun

  // get next unanswered email
  function handleNextEmail() {
    getNextEmail()
      .then((res) => {
        if (res.data.end) {
          history.push("/summary");
        } else {
          setAnswer({ answered: false, answer: false });
          setCurrentEmail(res.data);
          setMsg("");
        }
      })
      .catch((err) => history.push("/username"));
    fetchSigns().then((fSigns) => setSigns(fSigns));
  }

  // on page mount fetch next email
  useEffect(() => {
    handleNextEmail();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // handler for parsing and posting answer
  function handleAnswer(e) {
    setHelpWindowOpened(false);
    // player's answer
    let pAnswer = e.target.value === "true";
    // get type of current email
    let type = currentEmail["type"].type;
    // true if email is phishing (other type than legitimate), otherwise false
    let emailIsPhishing = type !== "legitimate";

    setAnswer({ answered: true, answer: pAnswer });

    // post answer, backend is handling current gamerun and email
    postAnswer(pAnswer);

    //if answer was correct and email is legitimate
    if (pAnswer === false && emailIsPhishing === false) {
      setMsg("Correct! This is a legitimate email");
    }
    // else if and was correct and email is phishing
    else if (pAnswer === true && emailIsPhishing === true) {
      setMsg("Correct! This is a phishing email (" + type + ")");
    }
    // else if answer was incorrect and email is phishing
    else if (pAnswer === false && emailIsPhishing === true) {
      setMsg("Wrong! This is a phishing email (" + type + ")");
    }
    // else if answer was incorrect and email is legitimate
    else {
      setMsg("Wrong! This is a legitimate email");
    }
  }

  // show/hide help window
  function handleHelpWindow() {
    setHelpWindowOpened(!helpWindowOpened);
  }

  function AnswerButton({ text, value }) {
    return (
      <Button
        variant="contained"
        sx={{ width: "110px" }}
        value={value}
        disabled={answer.answered}
        onClick={handleAnswer}
      >
        {text}
      </Button>
    );
  }

  // window with sender, subject and body of email
  // contains also answer buttons
  const emailWindow = (
    <Paper sx={{ width: "85%", height: "75vh", margin: "0 auto", padding: 3 }}>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          height: "100%",
        }}
      >
        <Box mb={2} sx={{ flex: "0 1 auto" }}>
          <Typography variant="h5">{currentEmail.subject}</Typography>
          <Typography variant="body2">{currentEmail.sender}</Typography>
        </Box>
        <Box sx={{ height: "100%", flex: "1 1 auto", overflow: "auto" }}>
          <Paper
            sx={{
              width: "100%",
              backgroundColor: "#a8a8a8",
              height: "100%",
            }}
          >
            <Typography
              sx={{ wordWrap: "break-word", padding: 2 }}
              variant="body2"
              color="black"
              width="100%"
            >
              {ReactHtmlParser(currentEmail.body)}
            </Typography>
          </Paper>
        </Box>
        <Box
          mt={2}
          sx={{
            display: "flex",
            flexDirection: "row",
            flex: "0 1 40px",
            justifyContent: "space-around",
          }}
        >
          {/* Legitimate button */}
          <AnswerButton text={"Legitimate"} value={false} />
          {/* Phishing button */}
          <AnswerButton text={"Phishing"} value={true} />
        </Box>
      </Box>
    </Paper>
  );

  // help window contains all signs,
  const helpWindow = (
    <Paper sx={{ height: 500, width: "90%", margin: "0 auto" }}>
      {/* Button, closes the window */}
      <Box sx={{ display: "flex", justifyContent: "flex-end" }}>
        <IconButton onClick={handleHelpWindow} color="primary">
          <CancelIcon />
        </IconButton>
      </Box>
      <Box sx={{ pl: 2, overflowY: "auto" }}>
        <Typography variant="h6">Hints</Typography>
      </Box>
      <Box
        sx={{
          height: "70%",
          px: 2,
          mt: 1,
          justifyContent: "center",
          overflowY: "auto",
        }}
      >
        {signs.map((sign, index) => {
          return (
            <Typography key={index} style={{ wordWrap: "break-word" }}>
              {index + 1}: {sign.text}
            </Typography>
          );
        })}
      </Box>
    </Paper>
  );

  // Indicators windows is shown when email is answered, contains signs of actual email
  function IndicatorsWindow() {
    return (
      <Paper sx={{ height: 500, width: "90%", margin: "0 auto" }}>
        <Box sx={{ padding: 2, overflowY: "auto" }}>
          <Typography variant="h6" sx={{ wordWrap: "break-word" }}>
            Indicators
          </Typography>
        </Box>
        <Box
          sx={{ padding: 2, overflowY: "auto", height: "75%", width: "100%" }}
        >
          {currentEmail.sign.map((sign, index) => {
            return (
              <Typography key={index} style={{ wordWrap: "break-word" }}>
                {index + 1}: {sign.text}
              </Typography>
            );
          })}
        </Box>
        <Box
          sx={{
            display: "flex",
            justifyContent: "flex-end",
            height: "8%",
          }}
        >
          {/* Next button, onlick gets next email of gamerun */}
          <Button
            variant="contained"
            color="primary"
            sx={{ mr: 2 }}
            onClick={handleNextEmail}
            size="medium"
          >
            Next
          </Button>
        </Box>
      </Paper>
    );
  }



  return (
    <Box sx={{ flexGrow: 1 }}>
      {/* Paper with message containing answer correctness and type of email */}
      <Grid container width="100%" rowSpacing={{ xs: 2, md: 10 }}>
        <Grid item width="100%" mt={1}>
          <Paper
            sx={{
              display: "flex",
              width: "90%",
              height: 100,
              justifyContent: "center",
              alignItems: "center",
              margin: "0 auto",
            }}
          >
            <Typography>{msg}</Typography>
          </Paper>
        </Grid>
        <Grid item container alignItems="center" width="100%">
          <Box
            component={Grid}
            item
            xs={helpWindowOpened || answer.answered ? 8 : 12}
            display={{
              // on small screens hide email window on answer post or help window opened
              xs: helpWindowOpened || answer.answered ? "none" : "block",
              sm: "block",
            }}
          >
            {emailWindow}
          </Box>
          <Grid
            item
            // if email has been answered or state for help window is false, hide help window
            hidden={!helpWindowOpened || answer.answered}
            xs={12}
            sm={4}
          >
            {helpWindow}
          </Grid>
          <Grid item hidden={!answer.answered} xs={12} sm={4}>
            {<IndicatorsWindow />}
          </Grid>
        </Grid>
      </Grid>

      {
        // if help window is closed and email is unanswered, show help button
        helpWindowOpened || answer.answered ? (
          ""
        ) : (
          <IconButton
            sx={{
              position: "absolute",
              margin: "auto",
              top: "50vh",
              right: 7,
            }}
            onClick={handleHelpWindow}
          >
            <HelpIcon color="primary" />
          </IconButton>
        )
      }
    </Box>
  );
}
