/* eslint-disable no-console */
import '../styles/fonts.css';
import '../styles/globals.css';
import '../styles/antd-fix.css';
import '../styles/antd.min.css';
import initializeQueryClient from '@/api/client';
import initializeApollo from '@/apollo/client';
import { Loading, Notification } from '@/Components/Common';
import Layout from '@/Components/Layout';
import { theme } from '@/config/ui';
import { withBasePath } from '@/config/urls';
import { usePageLoading } from '@/hooks';
import StoreProvider from '@/stores/Provider';
import getColors from '@/styles/colors';
import { GlobalStyle } from '@/styles/global-style';
import { trpcClient } from '@/trpc/client';
import { ApolloProvider } from '@apollo/client';
import { QueryClientProvider } from '@tanstack/react-query';
import Head from 'next/head';
import { useEffect, useMemo } from 'react';
import { ThemeProvider } from 'styled-components';
import { Config as AntdConfig } from 'ui/elements';

if (process.env.NODE_ENV === 'development') {
  require('../mocks');
}

const colorPrimary = getColors().COLOR_PRIMARY;

function App({ Component, pageProps }) {
  const { initialApolloState, initialQueryState } = pageProps;
  const apolloClient = useMemo(() => initializeApollo(initialApolloState), [initialApolloState]);
  const queryClient = useMemo(() => initializeQueryClient(initialQueryState), [initialQueryState]);

  const { loading } = usePageLoading();

  useEffect(() => {
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', () => {
        navigator.serviceWorker
          .register(withBasePath('/service-worker.js'))
          .then((registration) => {
            console.log('Service Worker registered:', registration);
          })
          .catch((error) => {
            console.error('Service Worker registration failed:', error);
          });
      });
    }
  }, []);

  return (
    <ThemeProvider theme={theme}>
      <Head>
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0"
        />
      </Head>
      <GlobalStyle />
      <StoreProvider {...pageProps}>
        <ApolloProvider client={apolloClient}>
          <QueryClientProvider client={queryClient}>
            <AntdConfig
              theme={{
                token: {
                  borderRadius: 2,
                  borderRadiusLG: 2,
                  colorLink: colorPrimary,
                  colorPrimary,
                },
              }}
            >
              <Notification>
                <Layout {...pageProps}>
                  {loading ? <Loading /> : <Component {...pageProps} />}
                </Layout>
              </Notification>
            </AntdConfig>
          </QueryClientProvider>
        </ApolloProvider>
      </StoreProvider>
    </ThemeProvider>
  );
}

export default trpcClient.withTRPC(App);
