import { useHistory } from 'react-router-dom';
import NavLink from '../../shared/buttons/nav-link';
import Button from '../../shared/buttons/button';
import ButtonGroup from '../../shared/buttons/button-group';
import { useUser } from '../../../hooks/react-query/use-user';
import { useLogoutMutation } from '../../../hooks/react-query/use-auth';
import { getLoginRedirectURL } from '../../utils/url';

type AuthHeaderProps = { className?: string };

function AuthHeader(props: AuthHeaderProps) {
  const history = useHistory();
  const { status, data: user } = useUser();
  const { mutate: logoutUser } = useLogoutMutation();

  if (status === 'error') {
    return (
      <ButtonGroup className={props.className}>
        <NavLink
          to={getLoginRedirectURL(history.location.pathname, history.location.search)}
          color='teal'
          colorWeight={600}
          content='ورود'
          className={props.className}
        />
        <NavLink
          to='/register'
          color='teal'
          colorWeight={600}
          content='ثبت نام'
          className={props.className}
        />
      </ButtonGroup>
    );
  }

  return (
    <ButtonGroup className={props.className}>
      <NavLink
        to='/home'
        color='teal'
        colorWeight={600}
        content={user?.name || user?.mobile}
        loading={status === 'loading'}
        disabled={status === 'loading'}
      />
      <Button
        content='خروج'
        color='red'
        colorWeight={500}
        onClick={logoutUser}
        loading={status === 'loading'}
        disabled={status === 'loading'}
      />
    </ButtonGroup>
  );
}

export default AuthHeader;
