import React from 'react';
import AsideNavigation from "@/jsx/Layouts/AsideComponents/AsideNavigation.jsx";
import AsideFooter from "@/jsx/Layouts/AsideComponents/AsideFooter.jsx";
import TabContent from "@/jsx/Layouts/ContentComponents/TabContent.jsx";

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      activeTab: this.props?.config?.tabs[0]?.name ?? null,
    };
  }

  componentDidMount() {

    const {config} = this.props;
    if (!config) {
      return;
    }

    // Get the tab from the URL
    const params = new URLSearchParams(window.location.search);
    const tabName = params.get('tab');
    if (tabName) {
      // Check if the tab name is valid
      const isValidTab = config.tabs.some(tab => tab.name === tabName);
      if (isValidTab) {
        this.setState({activeTab: tabName});
      }
      return;
    }

    // Get the first tab from the config
    const {tabs} = config;
    if (tabs && tabs.length > 0) {

      // Check if the active tab is already set
      if (this.state.activeTab === tabs[0].name) {
        return;
      }

      // Set the active tab to the first tab
      this.setState({activeTab: tabs[0].name});
    }

  }

  /**
   * Handle the tab change event
   * @param tabName
   */
  handleTabChange(tabName) {

    // Add the tab name to the URL
    const params = new URLSearchParams(window.location.search);
    params.set('tab', tabName);
    window.history.replaceState({}, '', `${window.location.pathname}?${params}`);

    // Set the active tab
    this.setState({activeTab: tabName});

  }

  render() {
    return (
      <>
        <div className="ra-aside-layout">
          <div className="ra-aside">
            <AsideNavigation
              {...this.props}
              activeTab={this.state.activeTab}
              onTabChange={this.handleTabChange.bind(this)}
            />
            <AsideFooter {...this.props}/>
          </div>
        </div>
        <div className="ra-content-layout">
          <TabContent
            {...this.props}
            activeTab={this.state.activeTab}
          />
        </div>
      </>
    );

  }

}
