import { SessionProvider } from "next-auth/react"
import type { Metadata } from "next"
import "../styles/styles.css"
import "../styles/global.css"
import "tailwindcss/tailwind.css"

import type { AppProps } from "next/app";
import type { Session } from "next-auth";
import { useEffect, useState } from "react"
import { useRouter } from "next/router";
import { NextIntlClientProvider } from 'next-intl';

// for fontawesome
import Head from 'next/head';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
// Use of the <SessionProvider> is mandatory to allow components that call
// `useSession()` anywhere in your application to access the `session` object.

// export const metadata: Metadata = {
//   title: "Специално Свидетелстване София",
//   description: "Специално Свидетелстване София",
//   viewport: "width=device-width, initial-scale=1",
//   appleWebApp: true,
// }


export default function App({ Component, pageProps: { session, ...pageProps }, }: AppProps<{ session: Session }>) {
  // console.log(pageProps);
  const router = useRouter();
  const [locale, setLocale] = useState(router.locale || 'bg');
  const [messages, setMessages] = useState({});

  useEffect(() => {
    console.log("Current locale:", router.locale);
    async function loadLocaleData() {
      // Replace the static import with a fetch request
      const res = await fetch(`/api/translations/${locale}`);
      if (res.ok) {
        const localeMessages = await res.json();
        console.log("Loaded messages for locale:", locale, localeMessages);
        setMessages(localeMessages);
      } else {
        const localeMessages = await import(`../content/i18n/${locale}.json`); setMessages(localeMessages.default);
      }
      console.log("Loaded locale '", locale, "' ",);
      //console.log("Loaded messages for locale:", router.locale, localeMessages.default);

    }
    loadLocaleData();
  }, [locale]);

  // useEffect(() => {
  //   async function loadLocaleData() {
  //     const locale = router.locale || 'en';
  //     const messages = await fetch(`/api/translations/${locale}`).then(res => res.json());
  //     setMessages(messages);
  //   }

  //   loadLocaleData();
  // }, [router.locale]);


  useEffect(() => {
    const use = async () => {
      (await import('tw-elements')).default;
    };
    use();
  }, []);


  // PUSH NOTIFICATIONS
  useEffect(() => {
    // Function to ask for Notification permission
    const askForNotificationPermission = async () => {
      // Check if the browser supports service workers and push notifications
      if ('serviceWorker' in navigator && 'PushManager' in window) {
        try {
          // Wait for service worker registration
          const registration = await navigator.serviceWorker.ready;
          // Ask for notification permission
          const permission = await Notification.requestPermission();
          if (permission === 'granted') {
            console.log('Notification permission granted.');
            // TODO: Subscribe the user to push notifications here
          } else {
            console.log('Notification permission not granted.');
          }
        } catch (error) {
          console.error('Error during service worker registration:', error);
        }
      } else {
        console.log('Service Worker or Push notifications not supported in this browser.');
      }
    };

    // Call the function to ask for permission on first load
    askForNotificationPermission();
  }, []);


  return (
    <>
      <NextIntlClientProvider
        locale={'bg'}
        timeZone="Europe/Sofia"
        messages={messages}
      >
        <SessionProvider session={session} >
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <Component {...pageProps} />
          </LocalizationProvider>
        </SessionProvider>
      </NextIntlClientProvider >
    </>
  )
}

// build time localization. Is it working for _app.tsx?d
// export async function getStaticProps(context) {
//   const messages = (await import(`../content/i18n/${locale}.json`)).default;
//   console.log("Loaded messages for locale:", locale, messages);
//   return {
//     props: {
//       // You can get the messages from anywhere you like. The recommended
//       // pattern is to put them in JSON files separated by locale and read
//       // the desired one based on the `locale` received from Next.js.
//       // messages: (await import(`../content/i18n/${context.locale}.json`)).default
//       messages
//     }
//   };
// }
