import { useEffect, useState } from "react";
import { Box, Skeleton, ThemeProvider } from "@mui/material";

import { StartPageViewPublication } from "./StartPageViewPublication";
import { Question } from "./Question";
import { ApologyPage } from "./ApologyPage"

import { useQuestionsStore } from "@root/quizData/store"
import { getData } from "@api/quizRelase"

import type { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
import { useGetSettings } from "../../utils/hooks/useGetSettings";
import { themesPublication } from "../../utils/themes/Publication/themePublication";
import { replaceSpacesToEmptyLines } from "./tools/replaceSpacesToEmptyLines";


const QID =
  process.env.NODE_ENV === "production" ?
    window.location.pathname.replace(/\//g, '')
    :
    "0bed8483-3016-4bca-b8e0-a72c3146f18b"


export const ViewPage = () => {
  const { settings, cnt, items } = useQuestionsStore()
  console.log("КВИЗ ", settings)
  console.log("ВОПРОСЫ ", items)


  const [visualStartPage, setVisualStartPage] = useState<boolean>();
  const [errormessage, setErrormessage] = useState<string>("");

  useEffect(() => {
    async function get() {
      try {
        let data = await getData(QID)

        console.log(data)
          //@ts-ignore
        const settings = data.settings

        console.log(data)
        //@ts-ignore
        data.settings = {
          //@ts-ignore
          qid: QID,
          fp: settings.fp,
          rep: settings.rep,
          name: settings.name,
          //@ts-ignore
          cfg: JSON.parse(data?.settings.cfg),
          lim: settings.lim,
          due: settings.due,
          delay: settings.delay,
          pausable: settings.pausable
        }
        console.log(data)
        //@ts-ignore
        data.items = data.items.map((item) => {
          const content = JSON.parse(item.c)
          return {
            description: item.desc,
            id: item.id,
            page: item.p,
            required: item.req,
            title: item.title,
            type: item.typ,
            content
          }
        }),
        console.log(data)
        console.log(JSON.stringify({data: data}).replaceAll(/\\\" \\\"/g, '""').replaceAll(/\" \"/g, '""'))
        console.log(JSON.parse(JSON.stringify({data: data}).replaceAll(/\\\" \\\"/g, '""').replaceAll(/\" \"/g, '""')).data)

        data = replaceSpacesToEmptyLines(data)

        useQuestionsStore.setState(JSON.parse(JSON.stringify({data: data}).replaceAll(/\\\" \\\"/g, '""').replaceAll(/\" \"/g, '""')).data)

      } catch (e) {

        //@ts-ignore
        if (e?.response?.status === 423) setErrormessage("квиз не активирован")
      }
    }
    get()
  }, [])


  useEffect(() => {//установка фавиконки
    if (Object.values(settings).length > 0) {

      const link = document.querySelector('link[rel="icon"]');
      if (link && settings?.cfg.startpage.favIcon) {
        link.setAttribute("href", settings?.cfg.startpage.favIcon);
      }

      setVisualStartPage(!settings?.cfg.noStartPage);
    }
  }, [settings]);


  const filteredQuestions = (
    items.filter(({ type }) => type) as AnyTypedQuizQuestion[]
  ).sort((previousItem, item) => previousItem.page - item.page);


  if (errormessage) return <ApologyPage message={errormessage} />
  if (visualStartPage === undefined) return <Skeleton sx={{ bgcolor: 'grey', width: "100vw", height: "100vh" }} variant="rectangular" />;
  if (cnt === 0 || (cnt === 1 && items[0].type === "result")) return <ApologyPage message="Нет созданных вопросов" />
  return (
    <ThemeProvider theme={themesPublication?.[settings?.cfg.theme || "StandardTheme"]}>
      <Box>
        {
          visualStartPage ?
            <StartPageViewPublication setVisualStartPage={setVisualStartPage} />
            :
            <Question questions={filteredQuestions} />
        }
      </Box>
    </ThemeProvider>

  );
};
