import React, { useState } from 'react'
import { useQuery, QueryClientProvider, QueryClient } from 'react-query'
import Head from 'next/head'

import Layout from '../components/layout'

import '../defaultStyles.css'
import constants from '../constants.json'

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: Infinity,
      refetchOnWindowFocus: 'always',
    },
  },
})

const getGlobalProps = () => {
  return new Promise((resolve) => {
    fetch(`${constants.apiUrl}infos?motd=true`, {
      credentials: 'include',
      Accept: 'application/json',
      'Content-Type': 'application/json',
    })
      .then((resp) => resp.json())
      .then((data) => {
        fetch(`${constants.apiUrl}hasNewMsg?userid=${data.uid}`, {
          credentials: 'include',
          Accept: 'application/json',
          'Content-Type': 'application/json',
        })
          .then((resp) => resp.json())
          .then((hasNewMsg) => {
            resolve({ ...data, ...hasNewMsg })
          })
          .catch((err) => {
            resolve({ ...data })
            console.error('Error getting unreads')
            console.error(err)
          })
      })
  })
}

function App({ Component, pageProps, router }) {
  const [globalState, setGlobalState] = useState({})
  const { data } = useQuery(['infos'], () => getGlobalProps(), {
    refetchOnWindowFocus: 'always',
  })

  const { motd, uid: userId, unreads } = data || {}

  const updateGlobalState = (newState) => {
    setGlobalState({
      ...globalState,
      ...newState,
    })
  }

  const globalData = {
    userId: userId,
    motd: motd,
    unreads: unreads,
  }

  return (
    <QueryClientProvider client={queryClient}>
      <Head>
        <meta
          name="viewport"
          content="initial-scale=0.8, width=device-width, user-scalable=no"
        />
      </Head>
      <Layout
        router={router}
        globalData={globalData}
        refetchGlobalData={() => queryClient.invalidateQueries(['infos'])}
        setGlobalState={updateGlobalState}
        globalState={globalState}
      >
        <Component
          {...pageProps}
          router={router}
          globalData={globalData}
          refetchGlobalData={() => queryClient.invalidateQueries(['infos'])}
          setGlobalState={updateGlobalState}
          globalState={globalState}
        />
      </Layout>
    </QueryClientProvider>
  )
}

export default function Root(props) {
  return (
    <QueryClientProvider client={queryClient}>
      <App {...props} />
    </QueryClientProvider>
  )
}
