/* eslint-disable react/jsx-props-no-spreading */
import { useState } from "react";
import { AppProps } from "next/app";
import { SessionProvider } from "next-auth/react";
import { CssBaseline } from "@mui/material";
import { CacheProvider, EmotionCache } from "@emotion/react";
import { AdapterDateFns } from "@mui/x-date-pickers-pro/AdapterDateFns";
import { LocalizationProvider } from "@mui/x-date-pickers-pro";
import createEmotionCache from "lib/createEmotionCache";
import "@fontsource/poppins/400.css";
import "@fontsource/poppins/700.css";
import "@fontsource/roboto/400.css";
import "@fontsource/roboto/700.css";
import "@fontsource/playfair-display/900.css";
import "styles/global.css";
import { LicenseInfo } from "@mui/x-data-grid-pro";
import { SWRConfig } from "swr";
import { GraphQLClient } from "graphql-request";

LicenseInfo.setLicenseKey(process.env.MUI_LICENSE_KEY);

const clientSideEmotionCache: any = createEmotionCache();

interface LinkWebProps extends AppProps {
  // eslint-disable-next-line react/require-default-props
  emotionCache?: EmotionCache;
}

export default function LinkWeb(props: LinkWebProps) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;

  const [csrfToken, setCsrfToken] = useState("");
  const origin =
    typeof window !== "undefined" && window.location.origin
      ? window.location.origin
      : null;
  const client = new GraphQLClient(`${origin}/graphql`, {
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
  });
  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 (
    <SessionProvider session={(pageProps as any).session}>
      <CacheProvider value={emotionCache}>
        <SWRConfig value={{ fetcher: graphQLFetcher }}>
          <CssBaseline />
          <LocalizationProvider dateAdapter={AdapterDateFns}>
            <Component {...pageProps} />
          </LocalizationProvider>
        </SWRConfig>
      </CacheProvider>
    </SessionProvider>
  );
}
