import React, { useState } from 'react'
import styles from './index.module.css'

interface TabProps {
  titles: Array<string>
  children: any,
  showIndex?: number,
  changeHandle?: Function
}

function Tab({ children, titles, showIndex = 1, changeHandle }: TabProps) {
  let [index, setIndex] = useState(showIndex - 1)

  if (!(children instanceof Array)) {
    children = [children]
  }
  if (titles.length < children.length) {
    let less = children.length - titles.length
    for (let i = 0; i < less; i++) {
      titles.push('Tab')
    }
  }

  const clickHandle = (i: number) => {
    setIndex(i)
    changeHandle && changeHandle(i + 1)
  }


  return (
    <div className={styles.tabLayer}>
      <div className={styles.headLayer}>
        {titles.map((title: string, i: number) => (
          <span
            key={i}
            className={index === i ? styles.active : ''}
            onClick={() => clickHandle(i)}>
            {title}
          </span>
        ))}
      </div>
      {children.map((Fn: any, i: number) => (
        <div className={index === i ? styles.showlayer : styles.hidelayer} key={i}>
          {Fn}
        </div>
      ))}
    </div>
  )
}

export default Tab