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

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

// biome-ignore lint/complexity/noBannedTypes: <intended>
export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
	// biome-ignore lint/suspicious/noExplicitAny: <known good>
	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"
						disableTransitionOnChange
						enableSystem
					>
						<Head>
							<title>Infoalloggi.it</title>
							<meta
								content="width=device-width, initial-scale=1.0, viewport-fit=cover"
								name="viewport"
							/>
							<meta
								content={
									locale === "it"
										? "Trova casa ora con Infoalloggi"
										: "Find your next home now!"
								}
								name="description"
							/>
						</Head>

						<style global jsx>{`
              :root {
                --font-inter: ${inter.style.fontFamily};
              }
            `}</style>

						<Toaster
							containerClassName="mt-10"
							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);
