import * as React from 'react'
import * as Styled from './index.style'

interface TabsProps {
  defaultValue?: string | number,
  value?: string | number,
  onChange?: (key: string) => void,
  children: React.ReactNode[] | null,
  innerRef?: any,
  color?: string,
  navHeight?: number,
  itemHeight?: number,
  activeColor?: string,
  navStyle?: React.CSSProperties,
}


interface TabPaneProps {
  title: string | React.ReactNode,
  value: string | number,
  children: React.ReactNode,
}

class TabPaneComponent extends React.Component<TabPaneProps> {
  render() {
    const { children } = this.props;
    return(
      <div>
        {children}
      </div>
    )
  }
}

class TabsComponent extends React.Component<TabsProps> {
  state = {
    activeValue: this.props.defaultValue ?? ''
  }

  element: any

  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      value: e.target.value
    })
    this.props.onChange?.(e.target.value)
  }

  componentWillReceiveProps(nextProps: Readonly<TabsProps>, nextContext: any): void {
    const newValue = nextProps.value;
    const oldValue = this.state.activeValue;
    if (newValue && newValue !== oldValue) {
      this.setState({
        activeValue: newValue,
      })
    }
  }

  public render() {
    const { children, color, navHeight, itemHeight, activeColor, navStyle } = this.props;
    const { activeValue } = this.state;
    return (
      <Styled.TabContainer>
        {
          children && children.length > 1 && (
            <Styled.Nav color={color} height={navHeight} style={navStyle}>
              {children && children.map((item: any) => (
                <Styled.NavItem
                  color={color}
                  key={item.props.value}
                  onClick={() => {
                    this.setState({
                      activeValue: item.props.value
                    })
                  }}
                  activeColor={activeColor}
                  height={itemHeight}
                  navHeight={navHeight}
                  total={children.length}
                  selected={activeValue === item.props.value}
                >
                  {
                    item.props.title
                  }
                </Styled.NavItem>
              ))}
            </Styled.Nav>
          )
        }
        <Styled.Content ref={this.props.innerRef}>
          {children && children.map((child: any) => {
            if (child.props.value !== activeValue) return undefined;
            return child.props.children;
          })}
        </Styled.Content>
      </Styled.TabContainer>
    )
  }
}

const TabPane = React.memo(TabPaneComponent);
const Tabs = React.forwardRef((props: TabsProps, ref: any) => {
  return <TabsComponent {...props} innerRef={ref} />
});

export {
  Tabs,
  TabPane,
}
