import { useRouter } from "next/router";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useQuery } from "react-query";
import {
  challengeParcours,
  getParcoursChallenge,
} from "../../requests/requests.room.js";
import { countOccurences, parseTimer } from "../../utils/utils.js";
import Input from "./InputExo.jsx";
import styles from "../../styles/room/parcours.module.scss";
import ParcoursExo from "./ParcoursExo.jsx";
import Layout from "../Layout.js";

export default function Parcours({ parcours_id, user, roomCode }) {
  const router = useRouter();
  const [exos, setExos] = useState([]);
  const [isCorr, setCorr] = useState({ isCorr: false, DOM: false }); //DOM pour useEffect 2 fois sinon les data-x apparaissent pas bien :(
  const [timer, setTimer] = useState(data && data.timer * 60);
  const [correctId, setCorrectId] = useState()
  const [data, setData] = useState();
  useEffect(() => {
    getParcoursChallenge(parcours_id, user.code).then((res) => {
      setData(res);
      setTimer(res.timer * 60);
      setCorrectId(res.correctId)
    });
    return () => {
      setData([]);
    };
  }, []);

  console.log("exos", data);
  /*  useEffect(() => {
    if (data) {
      setExos([
        ...data.exos.map((exo) => {
          return {
            order: exo.order,
            exos: exo.map((ex) => {
              let calcul = ex.calcul
                .replace("[", " [")
                .replace("]", "] ")
                .split(" ");
              if (
                !calcul
                  .map((c) => {
                    return c.startsWith("[") && c.endsWith("]");
                  })
                  .includes(true)
              ) {
                calcul.push("[]");
              }

              return {
                calcul: calcul.map((e) => {
                  return e.startsWith("[") && e.endsWith("]") ? (
                    <Input corr="" isCorr={isCorr.isCorr} calcul={ex.calcul} />
                  ) : (
                    e
                  );
                }),
              };
            }),
          };
        }),
      ]);
    }
  }, [data]); */
  const ref = useRef();

  useEffect(() => {
    if (data && timer > 0 && !isCorr.isCorr) {
      const time = setTimeout(() => {
        setTimer(timer - 1);
      }, 1000);
      return () => clearTimeout(time);
    } else if (data && timer <= 0) {
      ref.current.click();
    }
  }, [timer]);

  const formRef = useRef();
  const first = useRef(true);

  const [note, setNote] = useState({ value: null, total: null, isTrust: true });
  useLayoutEffect(() => {
    if (first.current) {
      first.current = false;
      return;
    }
    if (isCorr.isCorr == true && isCorr.DOM == false) {
      setCorr({ isCorr: true, DOM: true });
    }
    if (isCorr.isCorr == true && isCorr.DOM == true) {
      /*  console.log(
        formRef.current.elements,
        isCorr,
        formRef.current.elements.item(0).attributes
      ); */
      var target = formRef.current;
      //console.log("eee", target[0]);
      const resultList = [];
      for (var i = 0, element; (element = target[i++]); ) {
        if (element.type == "text") {
          resultList.push({
            idInput: element.getAttribute("data-idinput"),
            idExo: element.getAttribute("data-idexo"),
            idCalcul: element.getAttribute("data-idcalcul"),
            value: element.value,
          });
        }
      }
      var exosSend = data.exos.map((ex) => {
        var inputsExos = resultList.filter((e) => e.idExo == ex.order);
        return {
          ...ex,
          exos: ex.exos.map((e) => {
            return {
              ...e, inputs: e.inputs.map((i) => {
              return {...i, value: inputsExos.filter((inp)=>{return inp.idCalcul == e.order && inp.idInput == i.order})[0].value}
            })};
          }),
        };
      });
      console.log('DATASEND', exosSend)
      /* let isTrust = resultList.filter((r) => r.correct == null).length == 0;
      setNote({
        value: countOccurences(
          resultList.map((e) => {
            return e.correct;
          }),
          true
        ),
        total: resultList.length,
        isTrust: isTrust,
      });
 */
      challengeParcours({
        user_code: user.code,
        exos: {
          result: exosSend,
          timer: data.timer * 60 - timer,
        },
        id_code: parcours_id,
        correct_code: correctId
      }).then(res => {
        setData({ ...data, exos: res.exos })
        setNote(res.note)
      });
    }
    return () => {};
  }, [isCorr]);
  return (
    <Layout>
    <div>
      {data && (
        <>
          <div className={styles["head"]}>
            <h1>{data.name}</h1>
            <p className={timer < 60 ? styles["red"] : styles["green"]}>
              {parseTimer(timer)}
            </p>
          </div>
          <form
            ref={formRef}
            onSubmit={(e) => {
              e.preventDefault();
              setCorr({ isCorr: true, DOM: false });
            }}
          >
            {data &&
              data.exos
                .sort((a, b) => {
                  return a["order "] - b["order"];
                })
                .map((exo, i) => {
                  return (
                    <div className={styles["exo-full"]}>
                      <p>Exercice {exo.order + 1}</p>
                      {exo.exos
                        .sort((a, b) => {
                          return a.order - b.order;
                        })
                        .map((ex) => {
                          return (
                            <ParcoursExo
                              inputs={ex.inputs}
                              calcul={ex.calcul}
                              idExo={exo.order}
                              idCalcul={ex.order}
                              isCorr={isCorr.DOM}
                            />
                          );
                        })}
                    </div>
                  );
                })}
            {/* exos.map((exo, i) => {
              //onsole.log("exo", exo, exos);
              return (
                <div className={styles["exo-full"]}>
                  <p>Exercice {i + 1}</p>
                  <div className={styles["exo-container"]}>
                    {exo.map((ex, i) => {
                      // console.log(ex, "exxx", ex.calcul.includes(input));
                      return (
                        <div key={i}>
                          {ex.calcul.map((c) => {
                            if (typeof c == "string") {
                              return c + " ";
                            } else return c;
                          })}
                          {ex.calcul.includes(<input></input>) && (
                            <input></input>
                          )}
                        </div>
                      );
                    })}{" "}
                  </div>
                </div>
              );
            }) */}
            {!isCorr.isCorr && (
              <button ref={ref} className="exo-btn">
                Valider !
              </button>
            )}
          </form>
          <button
            onClick={() => {
              router.push(
                {
                  pathname: `/room/${roomCode}/${parcours_id}`,
                  query: { action: "view" },
                },
                undefined,
                { shallow: true }
              );
            }}
            className="cancel-btn"
          >
            Quitter
          </button>
          {note.value !== null && note.total !== null && (
            <p>
              {note.value}/{note.total}
              {note.total != 20 && `-> ${(note.value * 20) / note.total} / 20`}
              {!note.isTrust && "A corriger"}
            </p>
          )}
        </>
      )}
    </div> </Layout>
  );
}
