import { useEffect, useState } from "react";
import {
  correctParcours,
  getCorrectionInfo,
} from "../../requests/requests.room.js";
import { countOccurences, parseDate } from "../../utils/utils.js";
import Layout from "../Layout.js";
import CorrectionInput from "./CorrectionInput.jsx";
import InputExo from "./InputExo.jsx";
import ParcoursExo from "./ParcoursExo.jsx";

import styles from "../../styles/room/correction.module.scss";
import Back from "./back.jsx";
import { notificationService } from "../../services/notification.service.js";

export default function Correction({
  owner,
  parcours_id,
  user_code,
  correct_code,
  room_code,
}) {
  const [correctionMenu, setCorrectionMenu] = useState(null);
  const [correction, setCorrection] = useState();
  useEffect(() => {
    getCorrectionInfo({
      parcours_id: parcours_id,
      user_code: user_code,
      correct_code: correct_code,
    }).then((res) => {
      setCorrection(res);
    });
    return () => {
      setCorrection();
    };
  }, []);
  useEffect(() => {
    document.addEventListener("click", (e) => {
      if (correctionMenu != null) {
        setCorrectionMenu(null);
      }
    });
  });

  return (
    <Layout>
      <Back link={"/room/" + room_code + "/" + parcours_id} />
      <div>
        {correction && correction.parcours_name && (
          <div className={styles["head"]}>
            <h1 className={styles["title"]}>
              {correction.parcours_name}{" "}
              {correction.challenger_name && (
                <span>
                  - correction de{" "}
                  <span className="italic">{correction.challenger_name}</span>{" "}
                  le {parseDate(new Date(correction.endAt))}
                </span>
              )}
            </h1>
            <div className={styles.note}>
              <p
                className={
                  correction.note.isTrust
                    ? (correction.note.value * 20) / correction.note.total >= correction.success_condition
                      ? styles["success"]
                      : styles["fail"]
                    : styles["notTrust"]
                }
              >
                {correction.note.value}/{correction.note.total}
                {correction.note.total != 20 &&
                  ` = ${
                    Math.round(((correction.note.value * 20) / correction.note.total) * 100) / 100
                  } / 20`}
                {/* Round 2 decimals */}
                {!correction.note.isTrust && " (Note provisoire)"}
              </p>
            </div>
          </div>
        )}
        {correction && (
          <>
            {correction.result.map((exo) => {
              return (
                <div className={styles["exo"]}>
                  <p>Exercice {exo.order + 1}</p>
                  <div className={styles["exos-container"]}>
                    {exo.exos
                      .sort((a, b) => {
                        return a.order - b.order;
                      })
                      .map((ex) => {
                        return (
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              margin: "10px",
                            }}
                          >
                            {ex.calcul
                              .replace("[", " [")
                              .replace("]", "]")
                              .split(" ")
                              .map((c) => {
                                if (c.startsWith("[") && c.endsWith("]")) {
                                  var idInput = parseInt(
                                    c.replace("[", "").replace("]", "")
                                  );
                                  return (
                                    <CorrectionInput
                                      inputData={
                                        ex.inputs.filter(
                                          (i) => i.order == idInput
                                        )[0]
                                      }
                                      idInput={idInput}
                                      idExo={exo.order}
                                      idCalcul={ex.order}
                                      correctionMenu={
                                        correctionMenu ==
                                        `${exo.order}.${ex.order}`
                                      }
                                      setCorrectionMenu={(e) => {
                                        e.stopPropagation();
                                        if (owner) {
                                          setCorrectionMenu(
                                            correctionMenu ==
                                              `${exo.order}.${ex.order}`
                                              ? null
                                              : `${exo.order}.${ex.order}`
                                          );
                                        }
                                      }}
                                    />
                                  );
                                } else return c + " ";
                              })}
                          </div>
                        );
                      })}
                  </div>
                </div>
              );
            })}
            {owner && (
              <button
                className="exo-btn"
                onClick={() => {
                  var inputs = document.querySelectorAll("#correctionInput");
                  const correctionList = [];
                  for (var i = 0, element; (element = inputs[i++]); ) {
                    correctionList.push({
                      idInput: element.getAttribute("data-idinput"),
                      idExo: element.getAttribute("data-idexo"),
                      idCalcul: element.getAttribute("data-idcalcul"),
                      isCorrect:
                        element.getAttribute("data-iscorrect") != null
                          ? element.getAttribute("data-iscorrect") == "true"
                          : null,
                      correction: element.getAttribute("data-correction"),
                    });
                  }
                  var exosSend = correction.result.map((ex) => {
                    var inputsExos = correctionList.filter(
                      (e) => e.idExo == ex.order
                    );
                    return {
                      ...ex,
                      exos: ex.exos.map((e) => {
                        return {
                          ...e,
                          inputs: e.inputs.map((i) => {
                            return {
                              ...i,
                              correction: inputsExos.filter((inp) => {
                                return (
                                  inp.idCalcul == e.order &&
                                  inp.idInput == i.order
                                );
                              })[0].correction,
                              isCorrect: inputsExos.filter((inp) => {
                                return (
                                  inp.idCalcul == e.order &&
                                  inp.idInput == i.order
                                );
                              })[0].isCorrect,
                            };
                          }),
                        };
                      }),
                    };
                  });
                  let isTrust =
                    correctionList.filter((r) => r.isCorrect == null).length ==
                    0;
                  var note = {
                    value: countOccurences(
                      correctionList.map((e) => {
                        return e.isCorrect;
                      }),
                      true
                    ),
                    total: correctionList.length,
                    isTrust: isTrust,
                  };

                  correctParcours({
                    parcours_id: correction.parcours_id,
                    user_code: correction.user_code,
                    challenge_code: correction.code,
                    result: exosSend,
                    clientId: sessionStorage.getItem("clientId"),
                    note: note,
                    
                  }).then((res) => {
                    notificationService.success('Correction', 'Correction effectuée avec succès !')
                    setCorrection({...correction, ...res})
                  }).catch((err) => {
                    notificationService.error('Correction', 'Erreur lors de la correction !')
                  });
                }}
              >
                Valider
              </button>
            )}
          </>
        )}
      </div>
    </Layout>
  );
}
