/// <reference path="./definition.d.ts" />

import * as React from 'react';
import classNames from 'classnames';
import Hammer from 'react-hammerjs';
import Carousel from '../carousel';

const prefix = 'tsp-component-Tab';

class Tab extends React.Component<tspComponentTabProps, tspComponentTabState> {
  constructor(props: tspComponentTabProps, state: tspComponentTabState) {
    super(props, state);
  }

  public static defaultProps: tspComponentTabProps = {
    selectedIndex: 0,
    tabs: []
  };

  private carouselElem: HTMLElement;
  private bodyElem: HTMLElement;

  public state: tspComponentTabState = {
    selectedIndex: this.props.selectedIndex
  };

  public componentDidMount(): void {
    this.carouselElem = this.refs.carousel['refs'].container as HTMLElement;
    this.bodyElem = this.refs.body as HTMLElement;

    this.setHeight();
  }

  public componentDidUpdate(nextProps): void {
    if (nextProps.selectIndex !== this.props.selectedIndex) {
      this.setHeight();
    }
  }

  public setHeight(): void {
    this.bodyElem.style.height = this.carouselElem.clientHeight + 'px';
  }

  /**
   * 点击头部tab
   */
  public clickTab(selectedIndex: number): void {
    if (this.props.onChange) {
      this.props.onChange(selectedIndex);
    }
    this.setState({ selectedIndex }, () => this.setHeight());
  }

  public render(): JSX.Element {
    return (
      <div className={classNames({
        [prefix]: true,
        [this.props.className]: this.props.className
      })}>
        <div className={`${prefix}-head`}>
          {this.props.tabs.map((tab, i) => (
            <Hammer onTap={() => this.clickTab(i)} key={i}>
              <div
                className={classNames({
                  [`${prefix}-head-tab`]: true,
                  [`${prefix}-head-tab-selected`]: this.state.selectedIndex === i
                })}
              >{tab}</div>
            </Hammer>
          ))}
        </div>
        <div className={`${prefix}-body`} ref="body">
          <Carousel
            // width={this.props.width}
            selectedIndex={this.state.selectedIndex}
            swipeable={false}
            autoHeight
            ref="carousel"
          >
            {this.props.children}
          </Carousel>
        </div>
      </div>
    );
  }
}

export default Tab;