import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { getExos, getTags } from "../../requests/requests.exos.js";
import { createParcours } from "../../requests/requests.room.js";
import { isBrowser } from "../../utils/utils.js";
import SelectExo from "../pdf_gen/selectExo.jsx";

export default function CreateParcours({ roomCode, user }) {
  const [selected, setSelected] = useState([]);
  const [empty, setEmpty] = useState(false);
  const [exosList, setExos] = useState([]);
  const router = useRouter();
  useEffect(() => {
    getExos("web").then((exos) => {
      setExos([
        ...exos.map((d) => {
          return { ...d, numberInExo: 10, numberOfExo: 1 };
        }),
      ]);
    });
    return () => {
      setExos([]);
    };
  }, []);
  const [tags, setTags] = useState();
  useEffect(() => {
    console.log("test");
    getTags().then((tags) => {
      setTags([...tags]);
    });
    return () => {
      setTags([]);
    };
  }, []);
  const [options, setOptions] = useState({
    name: "parcourd test ",
    timer: 10,
  });

  return (
    <div>
      {exosList && tags && (
        <>
          {" "}
          <SelectExo
            exos={exosList}
            tagsData={tags}
            selected={selected}
            select={setSelected}
            emptyError={empty}
            setExos={setExos}
          />
          <input
            type="text"
            placeholder="Nom du parcours"
            value={options.name}
            onChange={(e) => {
              setOptions({ ...options, name: e.target.value });
            }}
          />
          <input
            type="number"
            placeholder="Timer (minutes)"
            value={options.timer}
            onChange={(e) => {
              setOptions({ ...options, timer: parseInt(e.target.value) });
            }}
          />
          <button
            className="exo-btn"
            onClick={() => {
              if (isBrowser) {
                createParcours({
                  ...options,
                  exos: exosList
                    .filter((e) => {
                      return selected.includes(e.id_code);
                    })
                    .map((ee) => {
                      return { id_code: ee.id_code, number: ee.numberInExo };
                    }),
                  room_code: roomCode,
                  code: user.code,
                }).then((r) => {
                  router.push({
                    pathname: "/room/" + roomCode + "/" + r.id_code,
                    query: { action: "view" }
                  }, undefined, {shallow: true});
                });
              }
            }}
          >
            Valider
          </button>
        </>
      )}
    </div>
  );
}
