import React, { memo, Fragment, useState, useCallback, useEffect } from 'react';
import { connect } from 'react-redux';
import TenantSelectModal from './TenantSelectModal';
import { getTenants, getUserInfo, switchUser } from 'models/user';
import styles from './Header.less';

function Header({ tenants, tenantId, tenantName, getTenants, getUserInfo, switchTenant }) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    getUserInfo();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tenantId]);

  const handleClick = useCallback(() => {
    setVisible((pre) => !pre);
  }, []);

  const handleClose = useCallback(() => {
    setVisible(false);
  }, []);

  const handleSelect = useCallback(
    (id) => {
      setVisible(false);
      if (tenantId !== id) {
        switchTenant(id, () => {
          window.location.reload();
        });
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [tenantId]
  );

  return (
    <Fragment>
      <div className={styles.header} onClick={handleClick}>
        <span className={styles.tenant}>{tenantName}</span>
      </div>
      <TenantSelectModal
        visible={visible}
        data={tenants}
        current={tenantId}
        onClose={handleClose}
        onSelect={handleSelect}
        getTenantList={getTenants}
      />
    </Fragment>
  );
}

function mapStateToProps({ user }) {
  const { tenants, userInfo } = user;

  return {
    tenants,
    tenantId: userInfo.tenantId,
    tenantName: userInfo.tenantName
  };
}

const mapDispatchToProps = {
  getTenants: getTenants,
  getUserInfo: getUserInfo,
  switchTenant: switchUser
};

export default connect(mapStateToProps, mapDispatchToProps)(memo(Header));
