import {
	createRootRoute,
	HeadContent,
	Outlet,
	Scripts,
} from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
import { useStore } from "@tanstack/react-store";
import { useEffect } from "react";
import { Toaster } from "sonner";
import { DefaultCatchBoundary } from "@/components/DefaultCatchBoundary";
import { NotFound } from "@/components/NotFound";
import { ThemeProvider } from "@/components/providers/theme-provider";
import LoadingScreen from "@/components/reusables/loading-screen";
import { AlertDialogProvider } from "@/components/ui/alert-dialog-provider";
import appCss from "@/global.css?url";
import { db } from "@/lib/db";
import {
	fixUser,
	initProfileStore,
	metaStore,
	profileStore,
	userMiddleware,
	userQuery,
	userUpdateCount,
} from "@/lib/db/user";
import { seo } from "@/utils/seo";

const headScript = `
    (function () {
      // Get theme from localStorage
      const theme = localStorage.getItem("vite-ui-theme") || "system";
      document.documentElement.classList.remove("light", "dark");

      if (theme === "system") {
        const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
          .matches
          ? "dark"
          : "light";

        document.documentElement.classList.add(systemTheme);
        return;
      }

      // Apply the theme to the document
      if (theme === "dark") {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.add("light");
      }
    })();

`;

const headStyle = `
    body {
      margin: 0;
      line-height: inherit;
    }

    *,
    ::before,
    ::after {
      box-sizing: border-box;
      /* 1 */
    }

    .light {
      background: #ffffff;
    }

    .dark {
      background: #171717;
    }

    .dark #preloader {
      background: #171717;
    }

    /* Full-page Loader */
    #preloader {
      position: fixed;
      width: 100%;
      height: 100%;
      background: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 9999;
    }

    /* Spinner */
    .spinner {
      width: 50px;
      height: 50px;
      border: 5px solid #ccc;
      border-top: 5px solid #3b82f6;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }
  `;

export const Route = createRootRoute({
	head: () => ({
		meta: [
			{
				charSet: "utf-8",
			},
			{
				name: "viewport",
				content: "width=device-width, initial-scale=1",
			},
			...seo({
				title: "1LC-CRM",
				description: `Site description here`,
			}),
		],
		links: [
			{ rel: "stylesheet", href: appCss },
			{
				rel: "apple-touch-icon",
				sizes: "180x180",
				href: "/apple-touch-icon.png",
			},
			{
				rel: "icon",
				type: "image/png",
				sizes: "32x32",
				href: "/favicon-32x32.png",
			},
			{
				rel: "icon",
				type: "image/png",
				sizes: "16x16",
				href: "/favicon-16x16.png",
			},
			{ rel: "manifest", href: "/site.webmanifest", color: "#fffff" },
			{ rel: "icon", href: "/favicon.ico" },
		],
		styles: [
			{
				id: "preloader-style",
				children: headStyle,
			},
		],
		scripts: [
			{
				id: "theme-init-script",
				children: headScript,
			},
		],
	}),
	pendingComponent: LoadingScreen,
	wrapInSuspense: true,
	errorComponent: DefaultCatchBoundary,
	notFoundComponent: () => <NotFound />,
	shellComponent: RootDocument,
	component: RootLayout,
	ssr: false,
});

function RootLayout() {
	const { user, isLoading } = db.useAuth();
	const { data, isLoading: isDataLoading } = db.useQuery(
		user ? userQuery(user) : null,
	);

	const updateCount = useStore(userUpdateCount);

	useEffect(() => {
		if (data && user) {
			if (updateCount > 1) {
				fixUser(user, data).then((isFixed) => {
					if (!isFixed) {
						initProfileStore(data);
					}
				});
			} else {
				userUpdateCount.setState((prev) => prev + 1);
			}
		} else {
			if (!isDataLoading) {
				// @ts-ignore
				profileStore.setState(() => null);
			}
		}
	}, [data, isDataLoading, user]);

	useEffect(() => {
		if (user) {
			metaStore.setState(() => user);
		} else {
			if (!isLoading) {
				// @ts-ignore
				metaStore.setState(() => null);
			}
		}
	}, [user]);

	return (
		<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
			<AlertDialogProvider>
				<Outlet />
				<Toaster richColors />
			</AlertDialogProvider>
		</ThemeProvider>
	);
}

function RootDocument({ children }: { children: React.ReactNode }) {
	return (
		<html className="size-full min-h-screen dark" lang="en">
			<head>
				<HeadContent />
			</head>
			<body className="size-full">
				{children}
				<TanStackRouterDevtools position="bottom-left" />
				<Scripts />
			</body>
		</html>
	);
}
