import { fetchSiteSettings } from "@/actions";
import { getSiteSettings } from "@/actions/cookies";
import { Toaster } from "@/components/ui/toaster";
import { FilterProvider } from "@/stores/productsFilter";
import { almarai } from "@/styels/fonts";
import { NextIntlClientProvider } from "next-intl";
import { getLocale, getMessages } from "next-intl/server";
import "react-phone-number-input/style.css";
import "./globals.css";
import Providers from "./providers";
import FooterRedesignThree from "./ui/shared/AdditionalFooters/FooterRedesignThree/FooterRedesignThree";
import OfflineStatus from "./ui/shared/DetectOffline";
import Maintance from "./ui/shared/Maintance";
import Navbar from "./ui/shared/Navbar";
import ScrollToTopButton from "./ui/shared/ScrollToTopBtn";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

export async function generateMetadata() {
  const res = await getSiteSettings();
  const settings = JSON.parse(res || "{}");
  const siteSettings = settings?.siteSetting;
  const images = settings?.images;

  return {
    title: siteSettings?.title,
    description: siteSettings?.description,
    icons: {
      icon: images?.favicon,
    },
  };
}

export default async function RootLayout({ children }) {
  const siteSetting = await fetchSiteSettings();
  const locale = await getLocale();
  const messages = await getMessages();
  const isUnderMaintenance = siteSetting?.site_settings?.maintenance == 1;
  const maintenanceMessage = siteSetting?.site_settings?.maintenance_message;
  const maintenanceTitle = siteSetting?.site_settings?.maintenance_title;

  return (
    <html lang={locale} dir={locale == "ar" ? "rtl" : "ltr"}>
      <body
        className={`${almarai.className} bg-body overflow-x-hidden max-lg:pb-16 flex flex-col min-h-screen`}
      >
        {isUnderMaintenance ? (
          <Maintance
            maintenanceMessage={maintenanceMessage}
            maintenanceTitle={maintenanceTitle}
          />
        ) : (
          <NextIntlClientProvider messages={messages}>
            <OfflineStatus />
            <Providers>
              <Navbar settingsResponse={siteSetting} />
              <FilterProvider>
                <div className="flex-1">{children}</div>
              </FilterProvider>
              <FooterRedesignThree siteSetting={siteSetting} />
              <ReactQueryDevtools initialIsOpen={false} />
            </Providers>
            <ScrollToTopButton />
            <Toaster />
          </NextIntlClientProvider>
        )}
      </body>
    </html>
  );
}
