import { useEffect } from 'react';
import { connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
import PropTypes from 'prop-types';
import { logoutUser } from '../../../redux/actions/auth';
import NavLink from '../../shared/buttons/nav-link';
import { fetchStudent } from '../../../redux/actions/student';
import ButtonGroup from '../../shared/buttons/button-group';
import Button from '../../shared/buttons/button';
import { fetchUserData } from '../../../redux/actions/user';
import { isAnonymous, isAuthenticated as isAuthenticatedFn } from '../../../redux/utils/auth';

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

  if (isAnonymous(props.authStatus)) {
    return (
      <ButtonGroup className={props.className}>
        <NavLink
          to={`/login?next=${nextURL}`}
          color='blue'
          content='ورود'
          className={props.className}
        />
        <NavLink
          to={`/register?next=${nextURL}`}
          color='blue'
          content='ثبت نام'
          className={props.className}
        />
      </ButtonGroup>
    );
  }

  const isAuthenticated = isAuthenticatedFn(props.authStatus);

  return (
    <ButtonGroup className={props.className}>
      <NavLink
        to='/profile'
        content={props.name}
        loading={!isAuthenticated || !props.name}
        disabled={!isAuthenticated || !props.name}
      />
      <Button
        content='خروج'
        color='red'
        onClick={props.logoutUser.bind(null, history)}
        loading={!isAuthenticated}
        disabled={!isAuthenticated}
      />
    </ButtonGroup>
  );
}

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

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

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