import '../styles/globals.css'
import NextProgress from 'next-progress'
import { useRouter, Router } from 'next/router'
import { AnimatePresence, motion } from 'framer-motion'
import { Toaster } from 'react-hot-toast'
import { QueryClient, QueryClientProvider } from 'react-query'
import useDevice from '@/core/hooks/useDevice'
import { useEffect, useState } from 'react'
import LogoSpinner from '@/core/components/elements/Spinner/LogoSpinner'

const queryClient = new QueryClient()

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  const { isMobile } = useDevice()

  const [animateLoader, setAnimateLoader] = useState(false)

  useEffect(() => {
    const handleRouteChangeStart = () => setAnimateLoader(true)
    const handleRouteChangeComplete = () => setAnimateLoader(false)

    Router.events.on('routeChangeStart', handleRouteChangeStart)
    Router.events.on('routeChangeComplete', handleRouteChangeComplete)
    Router.events.on('routeChangeError', handleRouteChangeComplete)

    return () => {
      Router.events.off('routeChangeStart', handleRouteChangeStart)
      Router.events.off('routeChangeComplete', handleRouteChangeComplete)
      Router.events.off('routeChangeError', handleRouteChangeComplete)
    }
  }, [])

  const [toasterStyle, setToasterStyle] = useState({})

  useEffect(() => {
    let elems = document.querySelectorAll('nav')
    let totalNavHeight = 0

    elems.forEach(function (elem) {
      totalNavHeight += elem.offsetHeight
    })

    setToasterStyle({
      marginTop: isMobile ? totalNavHeight - 8 : totalNavHeight
    })
  }, [isMobile])

  return (
    <>
      <AnimatePresence>
        {animateLoader && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{
              duration: 0.1
            }}
            className='fixed w-screen h-screen z-[500] bg-white flex justify-center items-center'
          >
            <LogoSpinner />
          </motion.div>
        )}
      </AnimatePresence>
      <Toaster
        position='top-center'
        containerStyle={toasterStyle}
        toastOptions={{
          duration: 3000,
          className: 'border border-gray_r-8'
        }}
      />
      <NextProgress color='#F01C21' options={{ showSpinner: false }} />
      <QueryClientProvider client={queryClient}>
        <AnimatePresence
          mode='popLayout'
          initial={false}
          onExitComplete={() => window.scrollTo(0, 0)}
        >
          {!animateLoader && <Component {...pageProps} key={router.asPath} />}
        </AnimatePresence>
      </QueryClientProvider>
    </>
  )
}

export default MyApp
