import React from "react";
import PropTypes from "prop-types";
import styles from "./DocsViewer.module.css";

class TabNamePart extends React.Component {
  constructor(props) {
    super(props);
    this.focusToSection = this.focusToSection.bind(this);
  }

  focusToSection() {
    this.props.onChange &&
      this.props.onChange(this.props.propId, () => {
        let focusTag = global.document.getElementById(this.props.propId);
        focusTag &&
          focusTag.scrollIntoView({ behavior: "smooth", block: "center" });
      });
  }

  render() {
    let activeClassName =
      this.props.propId === this.props.activeId ? styles.active : "";
    return (
      <li
        className={styles.tabs_item_box}
        onClick={this.focusToSection}
        role="tab"
        aria-selected={this.props.propId === this.props.activeId ? true : false}
        tabIndex={0}
        data-aria-listitem
        data-aria-navigation="37,38,39,40"
      >
        <span className={`${styles.tab__item} ${activeClassName}`}>
          {this.props.displayName}
        </span>
      </li>
    );
  }
}

TabNamePart.propTypes = {
  propId: PropTypes.string,
  activeId: PropTypes.string
};

export default class DocsTabs extends React.Component {
  constructor(props) {
    super(props);
    this.onChangeTab = this.onChangeTab.bind(this);
    this.state = {
      activeId: props.tabsList[0]
    };
  }

  onChangeTab(tabId, callback) {
    this.setState(
      {
        activeId: tabId
      },
      callback
    );
  }

  render() {
    let activeId = this.state.activeId;
    let props = this.props;

    return (
      <div className={styles.tabs_list_container}>
        <ul className={styles.tabs_list} role="tablist">
          {props.tabsList &&
            props.tabsList.map((itemId, index) => {
              let itemDisplayName =
                props.tabsDetail &&
                props.tabsDetail[itemId] &&
                props.tabsDetail[itemId].displayName;
              return (
                <TabNamePart
                  displayName={itemDisplayName}
                  propId={itemId}
                  activeId={activeId}
                  onChange={this.onChangeTab}
                  key={index}
                />
              );
            })}
        </ul>
      </div>
    );
  }
}
