import {useHistory} from 'react-router-dom';
import {useQueryClient} from 'react-query';
import PropTypes from 'prop-types';
import NavLink from '../../shared/buttons/nav-link';
import ButtonGroup from '../../shared/buttons/button-group';
import Button from '../../shared/buttons/button';
import {useUser} from '../../../hooks/user';
import {logoutUser} from '../../../api/auth';

function AuthHeader(props) {
  const history = useHistory();
  const {status, data: user} = useUser();
  const queryClient = useQueryClient();
  const nextURL = `${history.location.pathname}${history.location.search.replace('&', ';')}`;

  if (status === 'error') {
    return (
      <ButtonGroup className={props.className}>
        <NavLink
          to={`/login?next=${nextURL}`}
          color='blue'
          content='ورود'
          className={props.className}
        />
      </ButtonGroup>
    );
  }

  return (
    <ButtonGroup className={props.className}>
      <NavLink
        to='/profile'
        content={user?.name || user?.mobile}
        loading={status === 'loading'}
        disabled={status === 'loading'}
      />
      <Button
        content='خروج'
        color='red'
        onClick={() => logoutUser(queryClient, history)}
        loading={status === 'loading'}
        disabled={status === 'loading'}
      >
      </Button>
    </ButtonGroup>
  );
}

AuthHeader.propTypes = {
  className: PropTypes.string
};

export default AuthHeader;
