
import Head from 'next/head';
import { ThemeProvider } from '@mui/material/styles';
import theme from '../styles/muiTheme';
import {
  Hydrate,
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query';
import { Session } from "next-auth";
import { SessionProvider } from 'next-auth/react';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { appWithTranslation } from 'next-i18next';
import StorageProvider from '../store/cart-context';
import CheckoutProvider from '../store/checkout-context';
import UserProvider from '../store/user-context';
import Layout from '../components/layout/base-layout/Layout';
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { useState } from 'react';
import type { DehydratedState } from '@tanstack/react-query';

const Providers = ({ components, children }) => (
  <>
    {components.reduceRight(
      (acc, Comp) => (
        <Comp>{acc}</Comp>
      ),
      children
    )}
  </>
);

function MyApp({ Component, pageProps }: AppProps<{ dehydratedState: DehydratedState, session: Session }>) {
  const [queryClient] = useState(() => new QueryClient());
  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={pageProps.dehydratedState}>
        <SessionProvider session={pageProps.session}>
          <ThemeProvider theme={theme}>
            <Providers
              components={[CheckoutProvider, StorageProvider, UserProvider]}
            >
              <Layout>
                <Head>
                  <title>Coffee Shop</title>
                  <meta name="description" content="NextJS template" />
                  <meta
                    name="viewport"
                    content="width=device-width, initial-scale=1"
                  />
                </Head>
                <Component {...pageProps} />
              </Layout>
            </Providers>
          </ThemeProvider>
        </SessionProvider>
        <ReactQueryDevtools initialIsOpen={false}></ReactQueryDevtools>
      </Hydrate>
    </QueryClientProvider>)
}

export default appWithTranslation<never>(MyApp);
