import * as React from 'react';
import { HeaderTabs, Marker, ActiveComponent } from './Tabs.styled';

interface IProps {
  headers: string[];
}

export default class extends React.PureComponent<IProps> {
  static Panel = ActiveComponent;

  state = {
    activePanel: '',
    marker: {
      width: 0,
      index: 0
    }
  }
  tab = React.createRef();

  changeTabState = (element: HTMLLIElement) => this.setState({
    marker: { width: element.clientWidth, index: element.offsetLeft },
    activePanel: element.textContent
  })

  activatePanel = ({ currentTarget }: React.MouseEvent<HTMLLIElement, MouseEvent>) =>
    this.changeTabState((currentTarget as HTMLLIElement));

  componentDidMount() {
    // @ts-ignore
    this.changeTabState((this.tab.current.children[0] as HTMLLIElement));
  }

  render = () => {
    const { children, headers } = this.props;
    const { activePanel, marker } = this.state;
    return (
      <React.Fragment>
        <HeaderTabs
          // @ts-ignore
          ref={this.tab}
        >
          {headers.map((header, index) => (
            <li
              onClick={this.activatePanel}
              role='button'
              key={index}
              className={`tab-header-item-${index}`}
            >
              <a>{header}</a>
            </li>
          ))}
          <Marker marked={marker} />
        </HeaderTabs>
        { React.Children.map(children, (child: any) => (child.props.fromHeader === activePanel) && child) }
      </React.Fragment>
    )
  }
};
