import React, { useContext, useEffect } from 'react';
import {
  Avatar,
  Dropdown,
  Menu,
  Button
} from '@arco-design/web-react';
import {
  IconSettings,
  IconPoweroff,
  IconLoading
} from '@arco-design/web-react/icon';
import { useSelector, useDispatch } from 'react-redux';
import { GlobalContext } from '@/context';
import useLocale from '@/utils/useLocale';
import Settings from '../Settings';
import styles from './style/index.module.less';
import useStorage from '@/utils/useStorage';
import { generatePermission } from '@/routes';
import logoImage from '@/public/assets/logo.png';
import useUser from '@/hooks/user';
import { updateUserInfo } from '@/store/user';

function Navbar({ show }: { show: boolean }) {
  const t = useLocale();
  const { logoutHooks } = useUser();
  const { userInfo, userLoading } = useSelector((state) => state.user);
  const dispatch = useDispatch();

  const [_, setUserStatus] = useStorage('userStatus');
  const [role, setRole] = useStorage('userRole', 'admin');

  const { setLang, lang, theme, setTheme } = useContext(GlobalContext);

  function handleLogout() {
    setUserStatus('logout');
    logoutHooks();
  }

  function onMenuItemClick(key) {
    handleLogout();
  }

  useEffect(() => {
    dispatch(updateUserInfo({
      userInfo: {
        ...userInfo,
        permissions: generatePermission(role)
      }
    }));
  }, [role]);

  if (!show) {
    return (
      <div className={styles['fixed-settings']}>
        <Settings
          trigger={
            <Button icon={<IconSettings />} type="primary" size="large" />
          }
        />
      </div>
    );
  }

  const handleChangeRole = () => {
    const newRole = role === 'admin' ? 'user' : 'admin';
    setRole(newRole);
  };

  const droplist = (
    <Menu onClickMenuItem={onMenuItemClick}>
      <Menu.Item key="logout">
        <IconPoweroff className={styles['dropdown-icon']} />
        {t['navbar.logout']}
      </Menu.Item>
    </Menu>
  );

  const goHome = () => {
    window.location.href = '/dashboard/workplace';
  };

  return (
    <div className={styles.navbar}>
      <div className={styles.left}>
        <div className={styles.logo}>
          <img
            width={50}
            height={50}
            src={logoImage.src}
          />
          <div className={styles['logo-name']} onClick={() => goHome()}>工业软件组件化构建开发与运行支撑环境</div>
        </div>
      </div>
      <ul className={styles.right}>
        {userInfo && (
          <li>
            <Dropdown droplist={droplist} trigger="click" position="br" disabled={userLoading}>
              <Avatar size={32} style={{ cursor: 'pointer' }}>
                {userLoading ? (
                  <IconLoading />
                ) : (
                  <img alt="avatar" src={userInfo.avatar} />
                )}
              </Avatar>
            </Dropdown>
          </li>
        )}
      </ul>
    </div>
  );
}

export default Navbar;
