import React, {useEffect, useState} from 'react';
import {User} from '@/auth/auth.user';
import {useSystemContext} from '@/system/system.context';
import {YIcon} from '@/icon';
import {DesktopHeaderProps} from './desktop.interface';
import {HeaderMenuTitleStyle} from './desktop.styles';
import { 
  HeaderStyle, 
  HeaderRightStyle, 
  LogoStyle, 
  HeaderMenuStyle, 
  HeaderMenuItemStyle, 
  HeaderMenuCloseStyle
} from '../styles';
import {ModuleItem} from '../module/module.interface';
import {useModuleList} from '../module/useModuleList';


export const DesktopHeader: React.FC<DesktopHeaderProps> = ({ logo, menus, moduleName, moduleId, selectedKeys }) => {
  const {initDesktopMenu, selectModule} = useModuleList();
  const {store} = useSystemContext();
  const [state] = store();
  const [list, setList] = useState<ModuleItem[]>(menus);

  // const toggleLock = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, menu: any) => {
  //   e.stopPropagation();
  //   e.nativeEvent.stopImmediatePropagation();
  //   menu.toggleLock && menu.toggleLock(menu)
  // }

  const onClose = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, menu: any) => {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
    menu.onClose();
  }

  const onClick = (menu: any) => {
    selectModule(menu);
    menu.onClick();
  }

  useEffect(() => {
    initDesktopMenu(menus, moduleName, moduleId)
  }, []);

  useEffect(() => {
    setList(state.desktopMenus)
  }, [state.desktopMenus]);
  return (
    <HeaderStyle>
      <LogoStyle>{logo}</LogoStyle>
      {
        list && list.length ? (
          <HeaderMenuStyle mode="horizontal" selectedKeys={selectedKeys}>
          {
            list.map((menu: ModuleItem) => (
              <HeaderMenuItemStyle key={menu.name} onClick={() => onClick(menu)}>
                <HeaderMenuTitleStyle to={'/'}>
                  {
                    menu.meta && menu.meta.icon && (
                      <YIcon name={menu.meta.icon} size={14} color="#1890FF" />
                    )
                  }
                  <span>{menu.meta?.title}</span>
                </HeaderMenuTitleStyle>
                {
                  menu.onClose  && (
                    <>
                      <HeaderMenuCloseStyle onClick={(e) => onClose(e, menu)} className="close">
                        <YIcon name="CloseOutlined" size={10} />
                      </HeaderMenuCloseStyle>
                    </>
                  )
                }
                
              </HeaderMenuItemStyle>
            ))
          }
          </HeaderMenuStyle>
        ) : ''
      }
      <HeaderRightStyle>
        <User />
      </HeaderRightStyle>
    </HeaderStyle>
  )
};
