import { useEffect } from 'react';
import { connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap-button-loader';
import ButtonGroup from 'react-bootstrap/ButtonGroup';
import { logoutUser } from '../../../redux/actions/auth';
import { ANONYMOUS, AUTHENTICATED } from '../../../redux/constants';
import NavButton from '../../shared/nav-button';
import { fetchUserData } from '../../../redux/actions/user';
import { fetchData } from '../../utils/fetch';

function AuthHeader(props) {
  useEffect(() => fetchData(props.fetchUserData), [props.fetchUserData]);
  const history = useHistory();
  const nextURL = `${history.location.pathname}${history.location.search.replace('&', ';')}`;

  if (props.authStatus === ANONYMOUS) {
    return (
      <NavButton
        to={`/login?next=${nextURL}`}
        variant='outline-light'
        content='ورود'
        className={props.className}
      />
    );
  }

  const isAuthenticated = props.authStatus === AUTHENTICATED;

  return (
    <ButtonGroup className={props.className}>
      <NavButton
        to='/register'
        variant='light'
        loading={!isAuthenticated}
        disabled={!isAuthenticated}
        content={props.name || props.mobile}
      />
      <Button
        variant='danger'
        loading={!isAuthenticated}
        disabled={!isAuthenticated}
        onClick={props.logoutUser.bind(null, history)}
      >
        خروج
      </Button>
    </ButtonGroup>
  );
}

AuthHeader.propTypes = {
  authStatus: PropTypes.string.isRequired,
  name: PropTypes.string,
  mobile: PropTypes.string,
  fetchUserData: PropTypes.func.isRequired,
  logoutUser: PropTypes.func.isRequired
};

function mapStateToProps(state) {
  return {
    authStatus: state.auth.status,
    name: state.user.data.name,
    mobile: state.user.data.mobile
  };
}

export default connect(mapStateToProps, { fetchUserData, logoutUser })(AuthHeader);
