import React, { ReactNode, useEffect, useState } from 'react'
import jwt from 'jsonwebtoken'
import { mdiBackburger, mdiForwardburger, mdiMenu } from '@mdi/js'
import { useRouter } from 'next/router'
import menuAside from '../menuAside'
import menuNavBar from '../menuNavBar'
import BaseIcon from '../components/BaseIcon'
import NavBar from '../components/NavBar'
import NavBarItemPlain from '../components/NavBarItemPlain'
import AsideMenu from '../components/AsideMenu'
import FooterBar from '../components/FooterBar'
import Search from '../components/Search'
import { useAppDispatch, useAppSelector } from '../stores/hooks'
import { findMe, logoutUser } from '../stores/authSlice'
import { hasPermission } from '../helpers/userPermissions'
import { getLoginRoute } from '../helpers/workspace'

type Props = {
  children: ReactNode
  permission?: string
}

export default function LayoutAuthenticated({ children, permission }: Props) {
  const dispatch = useAppDispatch()
  const router = useRouter()
  const { token, currentUser } = useAppSelector((state) => state.auth)
  const bgColor = useAppSelector((state) => state.style.bgLayoutColor)
  const darkMode = useAppSelector((state) => state.style.darkMode)

  const [isAsideMobileExpanded, setIsAsideMobileExpanded] = useState(false)
  const [isAsideLgActive, setIsAsideLgActive] = useState(false)

  let localToken
  if (typeof window !== 'undefined') {
    localToken = localStorage.getItem('token')
  }

  const isTokenValid = () => {
    const storedToken = localStorage.getItem('token')

    if (!storedToken) return

    const date = new Date().getTime() / 1000
    const data: any = jwt.decode(storedToken)

    if (!data) return

    return date < data.exp
  }

  useEffect(() => {
    if (!isTokenValid()) {
      dispatch(logoutUser())
      router.replace(getLoginRoute(router.asPath))
      return
    }

    dispatch(findMe())
  }, [dispatch, localToken, router, token])

  useEffect(() => {
    if (!permission || !currentUser) return

    if (!hasPermission(currentUser, permission)) router.push('/error')
  }, [currentUser, permission, router])

  useEffect(() => {
    const handleRouteChangeStart = () => {
      setIsAsideMobileExpanded(false)
      setIsAsideLgActive(false)
    }

    router.events.on('routeChangeStart', handleRouteChangeStart)

    return () => {
      router.events.off('routeChangeStart', handleRouteChangeStart)
    }
  }, [router.events])

  const layoutAsidePadding = 'xl:pl-72'

  return (
    <div className={`${darkMode ? 'dark' : ''} overflow-hidden lg:overflow-visible`}>
      <div
        className={`${layoutAsidePadding} ${
          isAsideMobileExpanded ? 'ml-72 lg:ml-0' : ''
        } min-h-screen w-screen transition-position lg:w-auto ${bgColor} dark:bg-dark-800 dark:text-slate-100`}
      >
        <NavBar
          menu={menuNavBar}
          className={`${layoutAsidePadding} ${isAsideMobileExpanded ? 'ml-72 lg:ml-0' : ''}`}
        >
          <NavBarItemPlain
            display='flex lg:hidden'
            onClick={() => setIsAsideMobileExpanded(!isAsideMobileExpanded)}
          >
            <BaseIcon path={isAsideMobileExpanded ? mdiBackburger : mdiForwardburger} size='24' />
          </NavBarItemPlain>
          <NavBarItemPlain display='hidden lg:flex xl:hidden' onClick={() => setIsAsideLgActive(true)}>
            <BaseIcon path={mdiMenu} size='24' />
          </NavBarItemPlain>
          <NavBarItemPlain useMargin>
            <Search />
          </NavBarItemPlain>
        </NavBar>

        <AsideMenu
          isAsideMobileExpanded={isAsideMobileExpanded}
          isAsideLgActive={isAsideLgActive}
          menu={menuAside}
          onAsideLgClose={() => setIsAsideLgActive(false)}
        />

        <div className='pt-14'>
          <div className='min-h-[calc(100vh-3.5rem)]'>
            {children}
          </div>
          <FooterBar />
        </div>
      </div>
    </div>
  )
}
