import NotFound from '@/components/NotFound';
import { Toaster } from '@/components/ui/sonner';
import { getLocale } from '@paraglide/runtime';
import {
  CheckIcon,
  InfoIcon,
  WarningIcon,
  XCircleIcon,
} from '@phosphor-icons/react';
import { sessionQueries } from '@service/queries';
import { TanStackDevtools } from '@tanstack/react-devtools';
import type { QueryClient } from '@tanstack/react-query';
import {
  createRootRouteWithContext,
  HeadContent,
  Scripts,
} from '@tanstack/react-router';
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools';
import React from 'react';
import TanStackQueryDevtools from '../integrations/tanstack-query/devtools';
import appCss from '../styles.css?url';

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()(
  {
    beforeLoad: async ({ context }) => {
      const session = await context.queryClient.fetchQuery(
        sessionQueries.user(),
      );
      return { session };
    },
    head: () => ({
      meta: [
        {
          charSet: 'utf-8',
        },
        {
          name: 'viewport',
          content: 'width=device-width, initial-scale=1',
        },
        {
          title: 'Fuware',
        },
        {
          description: 'Fuware is a platform for managing your business.',
        },
      ],
      links: [
        {
          rel: 'stylesheet',
          href: appCss,
        },
      ],
    }),
    shellComponent: RootDocument,
    notFoundComponent: () => <NotFound />,
  },
);

function RootDocument({ children }: { children: React.ReactNode }) {
  return (
    <html lang={getLocale()}>
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <Toaster
          visibleToasts={5}
          position={'top-right'}
          offset={{ top: 60, right: 10 }}
          closeButton={true}
          icons={{
            success: <CheckIcon className="text-green-500" size={16} />,
            error: <XCircleIcon className="text-red-500" size={16} />,
            info: <InfoIcon className="text-blue-500" size={16} />,
            warning: <WarningIcon className="text-yellow-500" size={16} />,
          }}
        />
        <React.Suspense>
          <TanStackDevtools
            config={{
              position: 'bottom-right',
            }}
            plugins={[
              {
                name: 'Tanstack Router',
                render: <TanStackRouterDevtoolsPanel />,
              },
              TanStackQueryDevtools,
            ]}
          />
        </React.Suspense>
        <Scripts />
      </body>
    </html>
  );
}
