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 { ViewPage } from "./pages/ViewPublicationPage";
import { DesignPage } from "./pages/DesignPage/DesignPage";
import {
  Route,
  Routes,
  useLocation,
  useNavigate,
  Navigate,
} 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/ResultPage/Result";
import { ResultSettings } from "./pages/ResultPage/ResultSettings";
import MyQuizzesFull from "./pages/createQuize/MyQuizzesFull";
import Main from "./pages/main";
import EditPage from "./pages/startPage/EditPage";
import { Tariffs } from "./pages/Tariffs/Tariffs";
import {
  clearAuthToken,
  getMessageFromFetchError,
  useUserFetcher,
  UserAccount,
  makeRequest,
  devlog,
  createUserAccount,
} from "@frontend/kitui";
import {
  clearUserData,
  setUser,
  setUserAccount,
  setCustomerAccount,
  useUserStore,
} from "@root/user";
import { enqueueSnackbar } from "notistack";
import PrivateRoute from "@ui_kit/PrivateRoute";

import { Restore } from "./pages/startPage/Restore";

import { isAxiosError } from "axios";
import { useEffect, useLayoutEffect, useRef } from "react";
export function useUserAccountFetcher({
  onError,
  onNewUserAccount,
  url,
  userId,
}: {
  url: string;
  userId: string | null;
  onNewUserAccount: (response: UserAccount) => void;
  onError?: (error: any) => void;
}) {
  const onNewUserAccountRef = useRef(onNewUserAccount);
  const onErrorRef = useRef(onError);
  useLayoutEffect(() => {
    onNewUserAccountRef.current = onNewUserAccount;
    onErrorRef.current = onError;
  }, [onError, onNewUserAccount]);
  useEffect(() => {
    if (!userId) return;
    const controller = new AbortController();
    makeRequest<never, UserAccount>({
      url,
      contentType: true,
      method: "GET",
      useToken: true,
      withCredentials: false,
      signal: controller.signal,
    })
      .then((result) => {
        devlog("User account", result);
        onNewUserAccountRef.current(result);
      })
      .catch((error) => {
        devlog("Error fetching user account", error);
        if (isAxiosError(error) && error.response?.status === 404) {
          createUserAccount(controller.signal, url.replace("get", "create"))
            .then((result) => {
              devlog("Created user account", result);
              onNewUserAccountRef.current(result);
            })
            .catch((error) => {
              devlog("Error creating user account", error);
              onErrorRef.current?.(error);
            });
        } else {
          onErrorRef.current?.(error);
        }
      });
    return () => controller.abort();
  }, [url, userId]);
}

dayjs.locale("ru");

const routeslink = [
  {
    path: "/edit",
    page: EditPage,
    header: true,
    sidebar: true,
    footer: true,
  },
  {
    path: "/design",
    page: DesignPage,
    header: true,
    sidebar: true,
    footer: true,
  },
] as const;

export default function App() {
  const userId = useUserStore((state) => state.userId);
  const location = useLocation();
  const navigate = useNavigate();

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

  useUserAccountFetcher({
    url: "https://squiz.pena.digital/customer/account",
    userId,
    onNewUserAccount: setCustomerAccount,
    onError: (error) => {
      const errorMessage = getMessageFromFetchError(error);
      if (errorMessage) {
        enqueueSnackbar(errorMessage);
        clearUserData();
        clearAuthToken();
        navigate("/signin");
      }
    },
  });

  useUserAccountFetcher({
    url: "https://squiz.pena.digital/squiz/account/get",
    userId,
    onNewUserAccount: setUserAccount,
    onError: (error) => {
      const errorMessage = getMessageFromFetchError(error);
      if (errorMessage) {
        enqueueSnackbar(errorMessage);
        clearUserData();
        clearAuthToken();
        navigate("/signin");
      }
    },
  });

  if (location.state?.redirectTo)
    return (
      <Navigate
        to={location.state.redirectTo}
        replace
        state={{ backgroundLocation: location }}
      />
    );

  return (
    <>
      <ContactFormModal />
      {location.state?.backgroundLocation && (
        <Routes>
          <Route path="/signin" element={<SigninDialog />} />
          <Route path="/signup" element={<SignupDialog />} />
          <Route path="/restore" element={<Restore />} />
        </Routes>
      )}
      <Routes location={location.state?.backgroundLocation || location}>
        <Route path="/" element={<Landing />} />
        <Route
          path="/signin"
          element={
            <Navigate to="/" replace state={{ redirectTo: "/signin" }} />
          }
        />
        <Route
          path="/signup"
          element={
            <Navigate to="/" replace state={{ redirectTo: "/signup" }} />
          }
        />
        <Route
          path="/restore"
          element={
            <Navigate to="/" replace state={{ redirectTo: "/restore" }} />
          }
        />
        <Route path="/list" element={<MyQuizzesFull />} />
        <Route path={"/view"} element={<ViewPage />} />
        <Route path={"/tariffs"} element={<Tariffs />} />
        <Route element={<PrivateRoute />}>
          {routeslink.map((e, i) => (
            <Route
              key={i}
              path={e.path}
              element={
                <Main
                  Page={e.page}
                  header={e.header}
                  sidebar={e.sidebar}
                  footer={e.footer}
                />
              }
            />
          ))}
        </Route>
      </Routes>
    </>
  );
}
