import { useEffect, useState } from "react";
import { Box, Skeleton } 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";


const QID =
process.env.NODE_ENV === "production" ?
  window.location.pathname.replace(/\//g, '')
  :
  "e883eccc-78b0-47bb-98b9-66d2cb0cf51d"


export const ViewPage = () => {
  const { settings, cnt, items } = useQuestionsStore()

  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
        console.log(data)
        console.log(window.location.pathname.replace(/\//g, ''))
        const parseData = {
            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: 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
        }
        console.log(parseData)
         useQuestionsStore.setState(parseData)

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


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

    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]);


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


  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 (
    <Box>
      {
        visualStartPage ?
          <StartPageViewPublication setVisualStartPage={setVisualStartPage} />
          :
          <Question questions={filteredQuestions} />
      }
    </Box>
  );
};
