import React, { ReactNode, useEffect } from 'react'
import jwt from 'jsonwebtoken';
import menuNavBar from '../menuNavBar'
import NavBar from '../components/NavBar'
import NavBarItemPlain from '../components/NavBarItemPlain'
import FooterBar from '../components/FooterBar'
import { useAppDispatch, useAppSelector } from '../stores/hooks'
import { useRouter } from 'next/router'
import {findMe, logoutUser} from "../stores/authSlice";

import {hasPermission} from "../helpers/userPermissions";


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);

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

  const isTokenValid = () => {
    const token = localStorage.getItem('token');
    if (!token) return;
    const date = new Date().getTime() / 1000;
    const data = jwt.decode(token);
    if (!data) return;
    return date < data.exp;
  };

  useEffect(() => {
    dispatch(findMe());
    if (!isTokenValid()) {
      dispatch(logoutUser());
      router.push('/login');
    }
  }, [token, localToken]);

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

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

  const darkMode = useAppSelector((state) => state.style.darkMode)

  return (
    <div className={`${darkMode ? 'dark' : ''} overflow-hidden lg:overflow-visible`}>
      <div
        className={`pt-14 min-h-screen w-screen transition-position lg:w-auto ${bgColor}  dark:bg-dark-800 dark:text-slate-100`}
      >
        <NavBar
          menu={menuNavBar}
          className={`w-full`}
        >
          <NavBarItemPlain useMargin onClick={() => router.push('/dashboard')}>
            <div className="flex items-center space-x-2 px-4 py-2 cursor-pointer">
              <img 
                src="/logo.png" 
                alt="Trial Tracker Logo" 
                className="h-10 w-auto object-contain"
              />
            </div>
          </NavBarItemPlain>
        </NavBar>
        {children}
        <FooterBar>Hand-crafted & Made with ❤️</FooterBar>
      </div>
    </div>
  )
}