import ContactFormModal from "@ui_kit/ContactForm";
import ImageCrop from "@ui_kit/Modal/ImageCrop";
import dayjs from "dayjs";
import "dayjs/locale/ru";
import SigninDialog from "./pages/auth/Signin";
import SignupDialog from "./pages/auth/Signup";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import "./index.css";
import ContactFormPage from "./pages/ContactFormPage/ContactFormPage";
import InstallQuiz from "./pages/InstallQuiz/InstallQuiz";
import Landing from "./pages/Landing/Landing";
import QuestionsPage from "./pages/Questions/QuestionsPage";
import { Result } from "./pages/Result/Result";
import { Setting } from "./pages/Result/Setting";
import MyQuizzesFull from "./pages/createQuize/MyQuizzesFull";
import Main from "./pages/main";
import StartPage from "./pages/startPage/StartPage";
import { clearAuthToken, getMessageFromFetchError, useUserFetcher } from "@frontend/kitui";
import { clearUserData, setUser, useUserStore } from "@root/user";
import { enqueueSnackbar } from "notistack";


dayjs.locale("ru");

const routeslink = [
    { path: "/list", page: <MyQuizzesFull />, header: false, sidebar: false },
    { path: "/questions/:quizId", page: <QuestionsPage />, header: true, sidebar: true, },
    { path: "/contacts", page: <ContactFormPage />, header: true, sidebar: true },
    { path: "/result", page: <Result />, header: true, sidebar: true },
    { path: "/settings", page: <Setting />, header: true, sidebar: true },
    { path: "/install", page: <InstallQuiz />, header: true, sidebar: true },
] as const;

export default function App() {
    const userId = useUserStore((state) => state.userId);

    useUserFetcher({
        url: `https://hub.pena.digital/user/${userId}`,
        userId,
        onNewUser: setUser,
        onError: (error) => {
            const errorMessage = getMessageFromFetchError(error);
            if (errorMessage) {
                enqueueSnackbar(errorMessage);
                clearUserData();
                clearAuthToken();
            }
        },
    });

    return (
        <>
            <ContactFormModal />
            <BrowserRouter>
                <Routes>
                    {routeslink.map((e, i) => (
                        <Route key={i} path={e.path} element={<Main page={e.page} header={e.header} sidebar={e.sidebar} />} />
                    ))}
                    <Route path="setting/:quizId" element={<StartPage />} />
                    <Route path="crop" element={<ImageCrop />} />
                    <Route path="/" element={<Landing />} />
                    <Route path="/signin" element={<SigninDialog />} />
                    <Route path="/signup" element={<SignupDialog />} />
                </Routes>
            </BrowserRouter>
        </>
    );
}
