import { DefaultLayout } from "@Front/Components/LayoutTemplates/DefaultLayout";
import { FrontendVariables } from "@Front/Config/VariablesFront";
import "@Front/index.scss";
import type { NextPage } from "next";
import type { AppType, AppProps } from "next/app";
import type { ReactElement, ReactNode } from "react";

export type NextPageWithLayout<TProps = Record<string, unknown>, TInitialProps = TProps> = NextPage<TProps, TInitialProps> & {
	getLayout?: (page: ReactElement) => ReactNode;
};

type AppPropsWithLayout = AppProps & {
	Component: NextPageWithLayout;
} & {
	backApiProtocol: string;
	backApiHost: string;
	backApiPort: string;
	backApiRootUrl: string;
	backApiVersion: string;
	frontAppHost: string;
	frontAppPort: string;
	idNotAuthorizeEndpoint: string;
	idNotClientId: string;
};

const MyApp = (({
	Component,
	pageProps,
	backApiProtocol,
	backApiHost,
	backApiPort,
	backApiRootUrl,
	backApiVersion,
	frontAppHost,
	frontAppPort,
	idNotAuthorizeEndpoint,
	idNotClientId,
}: AppPropsWithLayout) => {
	const getLayout = Component.getLayout ?? ((page) => <DefaultLayout children={page}></DefaultLayout>);

	FrontendVariables.getInstance().BACK_API_PROTOCOL = backApiProtocol;
	FrontendVariables.getInstance().BACK_API_HOST = backApiHost;
	FrontendVariables.getInstance().BACK_API_PORT = backApiPort;
	FrontendVariables.getInstance().BACK_API_ROOT_URL = backApiRootUrl;
	FrontendVariables.getInstance().BACK_API_VERSION = backApiVersion;
	FrontendVariables.getInstance().FRONT_APP_HOST = frontAppHost;
	FrontendVariables.getInstance().FRONT_APP_PORT = frontAppPort;
	FrontendVariables.getInstance().IDNOT_AUTHORIZE_ENDPOINT = idNotAuthorizeEndpoint;
	FrontendVariables.getInstance().IDNOT_CLIENT_ID = idNotClientId;

	return getLayout(<Component {...pageProps} />);
}) as AppType;

MyApp.getInitialProps = async () => {
	return {
		backApiProtocol: process.env["BACK_API_PROTOCOL"],
		backApiHost: process.env["BACK_API_HOST"],
		backApiPort: process.env["BACK_API_PORT"],
		backApiRootUrl: process.env["BACK_API_ROOT_URL"],
		backApiVersion: process.env["BACK_API_VERSION"],
		frontAppHost: process.env["FRONT_APP_HOST"],
		frontAppPort: process.env["FRONT_APP_PORT"],
		idNotAuthorizeEndpoint: process.env["IDNOT_AUTHORIZE_ENDPOINT"],
		idNotClientId: process.env["IDNOT_CLIENT_ID"],
	};
};

export default MyApp;
