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

const GenQuestionsReport = ({ responsesByFilter, token }) => {
    const [genQuestionsResponse, setGenQuestionsResponse] = useState(null);

    const [genAnswersMean, setGenAnswersMean] = useState([]);
    const [genAnswersDistribution, setGenAnswersDistribution] = useState(null);

    // get genquestions by section's semester
    useEffect(() => {
        const trySetGenQuestions = async (section) => {
            if (section) {
                let semester = await fetchFromEndpoint(`/sections/${section}/`, token).then(response => response.json()).then(data => data);
                semester = semester.semester;

                const gen_questions = await fetchFromEndpoint(`/gen_questions/gen_question_per_semester/${semester}`, token).then(response => response.json()).then(data => data).catch(error => console.log(error));

                if (gen_questions)
                    setGenQuestionsResponse(gen_questions);
            }
        }

        if (responsesByFilter && responsesByFilter !== undefined) {
            const sections = () => { for (const response of responsesByFilter) return response.section }
            // get the answers for the first section because we assume
            // genanswers don't change much

            trySetGenQuestions(sections());
        }
    }, [responsesByFilter, token])

    useEffect(() => {
        const generateReport = () => {
            // construct all necessary data
            const gen_answers = [];

            // extract gen_answers
            responsesByFilter.map(response => gen_answers.push(response.gen_answers));

            // gen answers report
            // iterate per question
            let sum = 0;
            const genanswer_mean = [];
            const genanswer_distribution = {};

            if (gen_answers.length !== 0) {
                for (let i = 0; i < gen_answers[0].length; i++) {
                    genanswer_distribution[i] = {};
                    for (let j = 0; j < gen_answers.length; j++) {
                        sum += gen_answers[j][i];

                        // calculate distribution
                        if (genanswer_distribution[i][gen_answers[j][i]])
                            genanswer_distribution[i][gen_answers[j][i]] =
                                genanswer_distribution[i][gen_answers[j][i]] + 1;
                        else genanswer_distribution[i][gen_answers[j][i]] = 1;

                    }
                    genanswer_mean.push(sum / gen_answers.length);
                    sum = 0;
                }
            }

            setGenAnswersMean(genanswer_mean);
            setGenAnswersDistribution(genanswer_distribution);
        };

        if (responsesByFilter) generateReport()
    }, [responsesByFilter]);

    let genQuestionsRender =
        genQuestionsResponse &&
            responsesByFilter &&
            genAnswersMean.length !== 0 &&
            genAnswersDistribution ? (
            genQuestionsResponse.map((question, id) => (
                <tbody key={id}>
                    <tr>
                        <th colSpan={5}>
                            <strong style={{ display: "flex", justifyContent: "center" }}>
                                {question.text}
                            </strong>
                        </th>
                    </tr>
                    <tr>
                        <td>
                            <Stack>
                                <strong>I strongly agree</strong>
                                <strong>
                                    {genAnswersDistribution[id][5]
                                        ? Math.round(
                                            (genAnswersDistribution[id][5] /
                                                responsesByFilter.length) *
                                            100
                                        )
                                        : 0}
                                    %
                                </strong>
                            </Stack>
                        </td>
                        <td>
                            <Stack>
                                <strong>I agree moderately</strong>
                                <strong>
                                    {genAnswersDistribution[id][4]
                                        ? Math.round(
                                            (genAnswersDistribution[id][4] /
                                                responsesByFilter.length) *
                                            100
                                        )
                                        : 0}
                                    %
                                </strong>
                            </Stack>
                        </td>
                        <td>
                            <Stack>
                                <strong>I am not sure</strong>
                                <strong>
                                    {genAnswersDistribution[id][3]
                                        ? Math.round(
                                            (genAnswersDistribution[id][3] /
                                                responsesByFilter.length) *
                                            100
                                        )
                                        : 0}
                                    %
                                </strong>
                            </Stack>
                        </td>
                        <td>
                            <Stack>
                                <strong>I disagree moderately</strong>
                                <strong>
                                    {genAnswersDistribution[id][2]
                                        ? Math.round(
                                            (genAnswersDistribution[id][2] /
                                                responsesByFilter.length) *
                                            100
                                        )
                                        : 0}
                                    %
                                </strong>
                            </Stack>
                        </td>
                        <td>
                            <Stack>
                                <strong>I disagree strongly</strong>
                                <strong>
                                    {genAnswersDistribution[id][1]
                                        ? Math.round(
                                            (genAnswersDistribution[id][1] /
                                                responsesByFilter.length) *
                                            100
                                        )
                                        : 0}
                                    %
                                </strong>
                            </Stack>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <strong>Average responses {Math.round(genAnswersMean[id] * 100) / 100}</strong>
                        </td>
                    </tr>
                </tbody>
            ))
        ) : (
            <></>
        );

    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 Delivery {"("}
                            {responsesByFilter ? responsesByFilter.length : <></>}{" "}
                            evaluation{responsesByFilter ? responsesByFilter.length > 1 ? "s" : "" : <></>} received{")"}
                        </strong>
                    </th>
                </tr>
            </thead>
            {genQuestionsRender}
        </Table>
    )
}

export default GenQuestionsReport;