import React, { ComponentType, Component } from "react";

interface PageItem {
  Component: ComponentType<any>;
  props?: any;
}

interface PageCtrlState {
  pages: PageItem[];
}

export class PageCtrl extends Component<{}, PageCtrlState> {
  state = {
    pages: [],
  };

  static changePage: (Component: ComponentType<any>, props?: any) => void = null;
  static backPage: () => void = null;

  componentDidMount() {
    PageCtrl.changePage = this.changePage;
    PageCtrl.backPage = this.backPage;
  }

  componentWillUnmount() {
    PageCtrl.backPage = null;
    PageCtrl.backPage = null;
  }

  changePage = (Component: ComponentType<any>, props: any = {}) => {
    const pages = this.state.pages;
    pages.push({Component, props});
    this.setState({pages});
  };

  backPage = () => {
    const pages = this.state.pages;
    if (pages.length > 1) {
      pages.pop();
      this.setState({pages});
    }
  };

  render() {
    const { pages } = this.state;
    if (!pages.length) return null;
    const curPage = pages[pages.length - 1];
    return <curPage.Component {...curPage.props}/>;
  }
}
