import type { NextPage } from "next";
import type { AppProps } from "next/app";
import Head from "next/head";
import { useRouter } from "next/router";
import { type ComponentProps, type ReactElement, type ReactNode } from "react";
import { Toaster } from "react-hot-toast";
import "~/styles/globals.css";
import { api } from "~/utils/api";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { SessionProvider } from "~/providers/SessionProvider";
import { I18nProvider } from "~/providers/I18nProvider";
import { Layout } from "~/components/Layout";
import { inter } from "~/utils/fonts";
import "react-day-picker/dist/style.css";
import { NuqsAdapter } from "nuqs/adapters/next/pages";
import NextNProgress from "nextjs-progressbar";

type ThemeProviderProps = ComponentProps<typeof NextThemesProvider>;
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  getLayout?: (page: ReactElement<any>) => ReactNode;
};

type AppPropsWithLayout<P> = AppProps<P> & {
  Component: NextPageWithLayout<P>;
};

const MyApp = ({
  Component,
  pageProps,
}: AppPropsWithLayout<{ prop: null }>) => {
  const router = useRouter();
  const { locale } = router;

  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout || ((page) => <Layout>{page}</Layout>);

  return (
    <NuqsAdapter>
      <I18nProvider locale={locale}>
        <SessionProvider>
          <ThemeProvider
            attribute="class"
            defaultTheme="light"
            enableSystem
            disableTransitionOnChange
          >
            <Head>
              <title>Infoalloggi.it</title>
              <meta
                name="viewport"
                content="width=device-width, initial-scale=1.0"
              />
              <meta
                name="description"
                content={
                  locale === "it"
                    ? "Trova casa ora con Infoalloggi"
                    : "Find your next home now!"
                }
              />
            </Head>
            {/* eslint-disable-next-line react/no-unknown-property */}
            <style jsx global>{`
              :root {
                --font-inter: ${inter.style.fontFamily};
              }
            `}</style>

            <Toaster position="top-right" reverseOrder={false} />
            {!router.pathname.startsWith("/annunci") && (
              <NextNProgress options={{ showSpinner: false }} />
            )}

            {getLayout(<Component {...pageProps} />)}
          </ThemeProvider>
        </SessionProvider>
      </I18nProvider>
    </NuqsAdapter>
  );
};

export default api.withTRPC(MyApp);
