import React, { useEffect, useState } from "react";
import { Stack, Table } from "react-bootstrap";
import { fetchFromEndpoint } from "../../api/fetchFromEndpoint";

const IndividualSectionRender = ({ outcomes, mean, distribution }) => {
  return (
    <Table
      striped
      hover
      style={{
        letterSpacing: ".05rem",
        fontSize: 18,
        backgroundColor: "#F8F8F8",
      }}>
      <thead>
        <tr>
          <th colSpan={5}>
            <strong
              style={{
                display: "flex",
                justifyContent: "center",
                fontSize: 30,
              }}
            >
              Survey of Course Outcomes {"("}
              {distribution.responsesCount}{" "}
              evaluation{distribution.responsesCount > 1 ? "s" : ""} received{")"}
            </strong>
          </th>
        </tr>
      </thead>
      {outcomes.map((outcome, id) => (
        <tbody key={id}>
          {/*  heading row */}
          <tr>
            <th colSpan={5}>
              <strong style={{ display: "flex", justifyContent: "center" }}>
                {outcome.heading}
              </strong>
            </th>
          </tr>
          {/* questions rows */}
          {outcome.questions.map((question, idx) => (
            <React.Fragment key={idx}>
              <tr>
                <th colSpan={5}>
                  <h4 style={{ display: "flex", justifyContent: "center" }}>
                    {question}
                  </h4>
                </th>
              </tr>
              <tr>
                <td>
                  <Stack>
                    <strong>I agree strongly</strong>
                    <strong>
                      {distribution[idx][5]
                        ? Math.round(
                          (distribution[idx][5] /
                            distribution.responsesCount) *
                          100
                        )
                        : 0}
                      %
                    </strong>
                  </Stack>
                </td>

                <td>
                  <Stack>
                    <strong>I agree moderately</strong>
                    <strong>
                      {distribution[idx][4]
                        ? Math.round(
                          (distribution[idx][4] /
                            distribution.responsesCount) *
                          100
                        )
                        : 0}
                      %
                    </strong>
                  </Stack>
                </td>

                <td>
                  <Stack>
                    <strong>I am not sure</strong>
                    <strong>
                      {distribution[idx][3]
                        ? Math.round(
                          (distribution[idx][3] /
                            distribution.responsesCount) *
                          100
                        )
                        : 0}
                      %
                    </strong>
                  </Stack>
                </td>

                <td>
                  <Stack>
                    <strong>I disagree moderately</strong>
                    <strong>
                      {distribution[idx][2]
                        ? Math.round(
                          (distribution[idx][2] /
                            distribution.responsesCount) *
                          100
                        )
                        : 0}
                      %
                    </strong>
                  </Stack>
                </td>

                <td>
                  <Stack>
                    <strong>I disagree strongly</strong>
                    <strong>
                      {distribution[idx][1]
                        ? Math.round(
                          (distribution[idx][1] /
                            distribution.responsesCount) *
                          100
                        )
                        : 0}
                      %
                    </strong>
                  </Stack>
                </td>
              </tr>

              <tr>
                <td>
                  <strong>
                    Average responses {Math.round(mean[idx] * 100) / 100}
                  </strong>
                </td>
              </tr>
            </React.Fragment>
          ))}
        </tbody>
      ))}
    </Table>
  )
};

const CourseOutcomesReport = ({
  responsesByFilter,
  course,
  token,
}) => {
  const [organizedResponses, setOrganizedResponses] = useState(null);
  const [distribution, setDistribution] = useState(null);
  const [mean, setMean] = useState(null);
  const [outcomes, setOutcomes] = useState(null);

  // fetch all sections info
  useEffect(() => {
    const trySetOutcomes = async () => {
      const response = await fetchFromEndpoint(`/outcomes/course_outcomes/${course}/`, token).then(response => response.json()).then(data => data)
      if (response)
        setOutcomes(response);
    }

    if (course && token) trySetOutcomes();
  }, [course, token]);

  // organize structures
  useEffect(() => {
    if (responsesByFilter) {
      const orgRes = [];

      for (const response of responsesByFilter)
        orgRes.push(response.cs_answers);

      setOrganizedResponses(orgRes);
    }
  }, [responsesByFilter]);

  // generate report
  useEffect(() => {
    const genRep = () => {
      const means = [];
      const distrib = {};

      // i are questions
      for (let i = 0; i < organizedResponses[0].length; i++) {
        let sum = 0;
        distrib[i] = {}
        // j are the responses
        for (let j = 0; j < organizedResponses.length; j++) {
          sum += organizedResponses[j][i];

          // store distrib
          if (distrib[i][organizedResponses[j][i]])
            distrib[i][organizedResponses[j][i]] = distrib[i][organizedResponses[j][i]] + 1;
          else distrib[i][organizedResponses[j][i]] = 1;
        }

        means.push(sum / organizedResponses.length);
      }

      distrib.responsesCount = organizedResponses.length;

      setMean(means);
      setDistribution(distrib);
    }

    if (organizedResponses && organizedResponses.length > 0) genRep();
  }, [organizedResponses, responsesByFilter]);

  return (
    <div>
      {outcomes && mean && distribution ?
        (<IndividualSectionRender outcomes={outcomes} mean={mean} distribution={distribution} token={token} />) : <></>}
    </div>
  );
};

export default CourseOutcomesReport;
