import React from 'react';
import { i18n, TFunction } from 'i18next';
import App from 'next/app';
import Head from 'next/head';
import { NextRouter, useRouter } from 'next/router';
import { withTranslation, WithTranslation } from 'react-i18next';
import NextLink from '@digigov/nextjs/Link';
import DigiGOVApp, { StaticApp } from '@digigov/ui/app/App';
import type { AppProps } from '@digigov/ui/app/App';
import { I18NProvider } from '@digigov/ui/i18n';
import { LinkProvider } from '@digigov/ui/navigation/Link';

export interface DigiGOVNextAppProps extends AppProps, WithTranslation {
  children?: React.ReactNode;
  t: TFunction;
  i18n: i18n;
  ssr: boolean;
  router: NextRouter;
}
class DigiGOVNextAppClass extends App<DigiGOVNextAppProps> {
  render(): React.ReactElement {
    const { Component, pageProps, t, i18n, ssr = false, router } = this.props;
    const { locale } = router;

    if (locale && i18n.language != locale) {
      i18n.changeLanguage(locale);
    }
    return (
      <I18NProvider
        t={(str) => (typeof str === 'string' ? t(str) : str)}
        i18n={i18n}
      >
        <LinkProvider component={NextLink}>
          <Head>
            <meta
              name="viewport"
              content="minimum-scale=1, initial-scale=1, width=device-width"
            />
          </Head>
          {ssr ? (
            <DigiGOVApp>
              <Component {...pageProps} />
            </DigiGOVApp>
          ) : (
            <StaticApp>
              <Component {...pageProps} />
            </StaticApp>
          )}
        </LinkProvider>
      </I18NProvider>
    );
  }
}

const DigiGOVNextAppWithTranslation = withTranslation()(DigiGOVNextAppClass);
const DigiGOVNextApp = (props) => {
  const router = useRouter();
  return <DigiGOVNextAppWithTranslation {...props} router={router} />;
};
export default DigiGOVNextApp;
