import React, {useEffect, useState} from 'react';
import { Menu} from 'antd';
import {User} from '@/auth/auth.user';
import { HeaderStyle, HeaderRightStyle, LogoStyle, HeaderMenuStyle } from './styles';
import {HeaderProps, MenuItem } from './layout.interface';
import {useModel} from './useMenu';

export const Header: React.FC<HeaderProps> = ({ logo, menus }) => {
  const [menuList, setMenuList] = useState<MenuItem[]>([]);
  const { initMenus } = useModel();

  const initMenu = async () => {
    const res = await initMenus(menus);
    setMenuList(res);
  }

  const goToLogin = () => {
    if(typeof window === 'undefined'){

    } else {
      window.location.href='/login';
    }
    
  }

  useEffect(() => {
    let token = '';
    if(typeof window === 'undefined'){

    } else {
      token = window.localStorage.getItem("token") || "";
    }
    
    if(token && token !== '') {
      initMenu();
    } else {
      goToLogin();
    }
  }, []);
  
  return (
    <HeaderStyle>
      <LogoStyle>{logo}</LogoStyle>
      {
        menuList.length ? (
          <HeaderMenuStyle 
            mode="horizontal" 
          >
          {
            menuList.map((menu: MenuItem) => (
              <Menu.Item key={menu.path} onClick={menu.onClick}>{menu.meta?.title}</Menu.Item>
            ))
          }
          </HeaderMenuStyle>
        ) : ''
      }
      <HeaderRightStyle>
        <User />
      </HeaderRightStyle>
    </HeaderStyle>
  )
};
