import * as React from 'react';
import * as classNames from 'classnames';

import {PureComponent, ReactNode} from 'react';
import {MainNav} from './MainNav';
import {Drawer} from './Drawer';

export interface LayoutProps {
  breadcrumbs?: (string | ReactNode)[];
  children?: JSX.Element | JSX.Element[];
  drawerContent: ReactNode;
  drawerHeaderTitle: string;
  drawerOpen?: boolean;
  elementLeft?: ReactNode;
  elementRight?: ReactNode;
  loading?: boolean;
  mainNavTitle?: ReactNode;
  noMenuButton?: boolean;
  onDrawerClose?: () => void;
  onDrawerOpen?: () => void;
}

export interface LayoutState {
  drawerOpen: boolean;
}

export class Layout extends PureComponent<LayoutProps, LayoutState> {
  static defaultProps: Partial<LayoutProps> = {
    breadcrumbs: [],
    drawerOpen: false,
    elementLeft: null,
    elementRight: null,
    mainNavTitle: '',
    noMenuButton: false,
    loading: false,
    onDrawerClose: () => null,
    onDrawerOpen: () => null,
  };

  constructor(props: LayoutProps) {
    super(props);

    this.state = {
      drawerOpen: props.drawerOpen,
    };
  }

  componentWillReceiveProps(nextProps: LayoutProps) {
    if (nextProps.drawerOpen !== this.props.drawerOpen) {
      this.setState({drawerOpen: nextProps.drawerOpen});
    }
  }

  componentDidMount() {
    document.body.scrollTop = 0;
  }

  render() {
    const {
      breadcrumbs,
      children,
      drawerContent,
      drawerHeaderTitle,
      elementLeft,
      elementRight,
      loading,
      mainNavTitle,
      noMenuButton} = this.props;

    const {drawerOpen} = this.state;

    return (
      <div className="layout">
        <MainNav
          title={mainNavTitle}
          breadcrumbs={breadcrumbs}
          elementLeft={elementLeft}
          elementRight={elementRight}
          loading={loading}
          noMenuButton={noMenuButton}
          onClickMenuButton={this.openDrawer}
        />

        <Drawer
          open={drawerOpen}
          title={drawerHeaderTitle}
          onClose={this.closeDrawer}
        >
          {drawerContent}
        </Drawer>

        {children}
      </div>
    );
  }

  closeDrawer = () => {
    this.props.onDrawerClose();
    this.setState({drawerOpen: false});
  }

  openDrawer = () => {
    this.props.onDrawerOpen();
    this.setState({drawerOpen: true});
  }
}
