import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Container } from '../container/Container';
import { usePageContext } from './Page';

const propTypes = {
  actions: PropTypes.node,
  breadcrumb: PropTypes.node,
  secondaryActions: PropTypes.node,
  title: PropTypes.node,
  tag: PropTypes.elementType,
};

const defaultProps = {
  actions: '',
  breadcrumb: '',
  secondaryActions: '',
  title: '',
  tag: 'div',
};

export const PageTopbar = ({
  actions, breadcrumb, secondaryActions, title, tag: Tag,
}) => {
  const {
    size,
    gutterHorizontal,
    isContentScrolled,
    setRangeAnimationShouldNotStart,
    shouldNotAnimateTopBar,
  } = usePageContext();

  const topBarRef = useRef();

  useEffect(() => {
    if (topBarRef.current) {
      const TOPBAR_SIZE = 36;

      setRangeAnimationShouldNotStart(TOPBAR_SIZE);
    }
  }, [topBarRef.current]);

  return (
    <Tag
      className={`sui-l-app-layout__page-topbar ${isContentScrolled ? 'as--fixed' : ''} ${shouldNotAnimateTopBar ? 'as--bordered' : ''}`}
      ref={topBarRef}
    >
      <Container size={size} gutterVertical="none" gutterHorizontal={gutterHorizontal}>
        {(!!breadcrumb || !!secondaryActions) && (
          <div className="sui-l-app-layout__page-topbar-secondary">
            <div className="sui-g-grid as--auto as--middle as--no-wrap">
              <div className="sui-g-grid__item as--fill">
                {breadcrumb}
              </div>
              <div className="sui-g-grid__item as--flex-none">
                {secondaryActions}
              </div>
            </div>
          </div>
        )}
        {(!!title || !!actions) && (
          <div className="sui-l-app-layout__page-topbar-primary">
            <div className="sui-g-grid as--auto as--middle as--no-wrap">
              <div className="sui-g-grid__item as--fill">
                <div className="sui-l-app-layout__page-topbar-title">
                  {title}
                </div>
              </div>
              <div className="sui-g-grid__item as--flex-none">
                <div className="sui-l-app-layout__page-topbar-actions">
                  {actions}
                </div>
              </div>
            </div>
          </div>
        )}
      </Container>
    </Tag>
  );
};

PageTopbar.propTypes = propTypes;
PageTopbar.defaultProps = defaultProps;
