import Paper from "@mui/material/Paper";
import Box from "@mui/material/Box";
import { Button, Container, Typography } from "@mui/material";
import { Fragment, useEffect, useState } from "react";
import Grid from "@mui/material/Grid";
import axios from "axios";
import { Link, Redirect } from "react-router-dom";
import CheckIcon from "@mui/icons-material/Check";
import CloseIcon from "@mui/icons-material/Close";
import { useHistory, useLocation } from "react-router";
import { fetchCurrentGamerunSummary } from "../helpers/gameruns";
import ReactHtmlParser from "react-html-parser";

// Page with summary of current player's gamerun
export default function SummaryPage() {
  // msg, containing username and number of correct answers
  const [msg, setMsg] = useState();
  const username = localStorage.getItem("username");
  // emails of current gamerun also containing statistics
  const [emailsWStatistics, setEmailsWStatistics] = useState([]);
  const history = useHistory();

  const countCorrectAnswers = (emails) => {
    return emails.filter((email) => email.answer.correctness === true).length;
  };

  useEffect(() => {
    fetchCurrentGamerunSummary()
      .then((data) => {
        setEmailsWStatistics(data);
        setMsg(
          username +
            ", You have " +
            countCorrectAnswers(data) +
            "/" +
            data.length +
            " correct"
        );
      })
      .catch((err) => {
        history.push("/username");
      });
  }, []);

  // Play again button, located on top and bottom of page, redirects to username page
  const PlayAgainButton = () => (
    <Box
      sx={{
        display: "flex",
        width: "100%",
        justifyContent: "center",
        my: 4,
      }}
    >
      <Button
        sx={{ marginX: "auto" }}
        variant="contained"
        component={Link}
        to="/username"
      >
        play again
      </Button>
    </Box>
  );

  // Paper contains email subject, sender, body
  const EmailWindow = ({ email }) => {
    return (
      <Paper
        sx={{
          width: "100%",
          height: 370,
          padding: 2,
        }}
      >
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            width: "100%",
            height: "100%",
          }}
        >
          <Typography variant="h6">{email.subject}</Typography>
          <Typography variant="body2">{email.sender}</Typography>
          <Paper
            sx={{
              width: "100%",
              height: "100%",
              overflowY: "auto",
              border: 1,
              backgroundColor: "#a8a8a8",
            }}
          >
            <Typography
              sx={{ wordWrap: "break-word", padding: 2 }}
              variant="body2"
              color="black"
            >
              {ReactHtmlParser(email.body)}
            </Typography>
          </Paper>
        </Box>
      </Paper>
    );
  };

  const StatisticsPaper = ({ email }) => {
    return (
      <Paper
        sx={{
          width: "100%",
          height: 370,
          padding: 2,
          display: "flex",
          flexDirection: "column",
        }}
      >
        <Typography>
          Average correctness: {email.average_correctness}%
        </Typography>
        <Typography>Your time: {email.players_duration}</Typography>
        <Typography>Average duration: {email.average_duration}</Typography>
        <Box
          sx={{
            display: "flex",
            flex: 1,
            flexDirection: "column",
            justifyContent: "flex-end",
          }}
        >
          <Typography variant="h6">
            Your answer:
            {
              // if answer is true = "Phishing", otherwise "Legitimate"
              email.answer.player_answer === true ? "Phishing" : "Legitimate"
            }
            {
              // if answer was correct, show check icon, otherwise X
              email.answer.correctness === true ? (
                <CheckIcon sx={{ color: "green" }} />
              ) : (
                <CloseIcon sx={{ color: "red" }} />
              )
            }
          </Typography>
        </Box>
      </Paper>
    );
  };

  return (
    <div>
      {/* Paper with message (username and number of correct answers)*/}
      <Paper
        sx={{
          width: "95%",
          height: "10vh",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          margin: "auto",
          mt: 1,
        }}
      >
        {msg}
      </Paper>
      <PlayAgainButton />
      <Container>
        <Grid container rowSpacing={10}>
          {
            // map emails into email window and statistics
            emailsWStatistics.map((email, index) => (
              <Grid item container rowSpacing={2} columnSpacing={4}>
                {/* Email window */}
                <Grid item sm={1} />
                <Grid item container xs={12} sm={6} justifyContent="center">
                  <EmailWindow email={email.email} />
                </Grid>
                {/* Paper with statistics */}
                <Grid item container xs={12} sm={4} justifyContent="center">
                  <StatisticsPaper email={email} />
                </Grid>
                <Grid item sm={1} />
              </Grid>
            ))
          }
        </Grid>
      </Container>
      {PlayAgainButton}
    </div>
  );
}
