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, '')
    :
    "9fafc6c9-6ccf-42b6-b400-0ee9f5f0fa16"


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 {
        const data = await getData(QID)
        //@ts-ignore
        const settings = data.settings
        const parseData = replaceSpacesToEmptyLines({
          settings: {
            //@ts-ignore
            qid: QID,
            fp: settings.fp,
            rep: settings.rep,
            name: settings.name,
            cfg: JSON.parse(settings?.cfg),
            lim: settings.lim,
            due: settings.due,
            delay: settings.delay,
            pausable: settings.pausable
          },
          //@ts-ignore
          items: 
            //@ts-ignore
            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
              }
            }),
          //@ts-ignore
          cnt: data.cnt
        })


        parseData.items = parseData.items.map((question:any) => {
          let data = question
          for (let key in question) {
              if (question[key] === " ") data[key] = ""
            }
            return data
      })
  



        useQuestionsStore.setState(parseData)

      } 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>

  );
};
