"use client";

import { FC, PropsWithChildren, useState } from "react";
import { CssBaseline } from "@mui/material";
import { CookiesProvider } from "react-cookie";
import { SessionProvider } from "next-auth/react";
import { NextAppDirEmotionCacheProvider } from "tss-react/next/appDir";
import { SWRConfig } from "swr";
import { GraphQLClient } from "graphql-request";
import { I18n } from "react-polyglot";
import { AdapterDateFns } from "@mui/x-date-pickers-pro/AdapterDateFns";
import { LocalizationProvider } from "@mui/x-date-pickers-pro";
import { LicenseInfo } from "@mui/x-date-pickers-pro";
import { locales } from "leafcutter-common";

LicenseInfo.setLicenseKey(
  "7c9bf25d9e240f76e77cbf7d2ba58a23Tz02NjU4OCxFPTE3MTU4NjIzMzQ2ODgsUz1wcm8sTE09c3Vic2NyaXB0aW9uLEtWPTI=",
);

export const MultiProvider: FC<PropsWithChildren> = ({ children }) => {
  const [csrfToken, setCsrfToken] = useState("");
  const origin =
    typeof window !== "undefined" && window.location.origin
      ? window.location.origin
      : null;
  const client = new GraphQLClient(`${origin}/zammad/graphql`, {
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
  });
  const messages: any = { en: locales.en, fr: locales.fr };
  const locale = "en";
  const graphQLFetcher = async ({ document, variables }: any) => {
    const requestHeaders = {
      "X-CSRF-Token": csrfToken,
    };
    const { data, headers } = await client.rawRequest(
      document,
      variables,
      requestHeaders,
    );

    const token = headers.get("CSRF-Token");
    setCsrfToken(token);

    return data;
  };

  return (
    <>
      <CssBaseline />
      <NextAppDirEmotionCacheProvider options={{ key: "css" }}>
        <SWRConfig value={{ fetcher: graphQLFetcher }}>
          <SessionProvider>
            <CookiesProvider>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
                <I18n locale={locale} messages={messages[locale]}>
                  {children}
                </I18n>
              </LocalizationProvider>
            </CookiesProvider>
          </SessionProvider>
        </SWRConfig>
      </NextAppDirEmotionCacheProvider>
    </>
  );
};
