import * as React from "react"
import styled, { css } from "styled-components"

const TabIndicatorStyle = css`
  ${(props: any) => {
    const p = 100 / props.tabs.length
    return props.tabs.map((t, i) => {
      // calculate range per item
      return `
        &:nth-child(${i + 1}).is-active {
          color: ${props.theme.pumpkin};
          font-weight: bold;
        }
        &:nth-child(${i +
          1}).is-active ~ .TabNavigation__indicator:last-child:after {
          left: ${i * p}%;
        }
      `
    })
  }};
`
const IndicatorWidthStyle = css`
  width: ${(props: any) => props.width}px;
`
const TabNavigationStyleComponent = styled.div.attrs<{
  tabs: any[]
  width?: number
}>({
  className: "TabNavigation"
})`
  display: block;
  border-bottom: 2px solid ${(props) => props.theme.borderGrey};

  .TabNavigation-wrapper {
    position: relative;
    display: inline-block;
    padding: 13px 0;
  }

  .TabNavigation__indicator {
    font-size: 1.5rem;
    font-family: -DB-HeaventRounded, Thonburi, Tahoma, Arial, sans-serif;
    display: inline-block;
    text-align: center;
    cursor: pointer;
    user-select: none;
    color: ${(props) => props.theme.darkGrey};
    min-width: 120px;

    ${TabIndicatorStyle} ${IndicatorWidthStyle}

    &:last-child:after {
      transition: 0.222s all ease-in-out;
      content: " ";
      min-width: 120px;
      height: 4px;
      background-color: ${(props) => props.theme.pumpkin};
      position: absolute;
      bottom: -2px;
      left: ${(props: any) => {
        const p = 100 / props.tabs.length
        return (props.tabs.length - 1) * p
      }}%;
      ${IndicatorWidthStyle};
    }
  }
`

/**
 * Tab will display multiple page
 * and switch by tab
 * - unactive tab will be unmount by default ( forceMount: true if you want to disable this feature )
 *
 */

export type TabNavigationPropTypes = {
  activeTabIndex: number
  onSelectTab: (index: number) => void
  tabs: Array<{ key: string; name: string }>
  tabWidth?: number

  forceMount?: boolean
}

export const TabNavigation: React.SFC<TabNavigationPropTypes> = (props) => {
  const { activeTabIndex, tabs, onSelectTab } = props
  const onClick = (i) => () => onSelectTab(i)
  return (
    <TabNavigationStyleComponent width={props.tabWidth} tabs={tabs}>
      <div className="TabNavigation-wrapper">
        {tabs.map((tab, i) => {
          return (
            <div
              onClick={onClick(i)}
              key={tab.key}
              className={`TabNavigation__indicator ${
                i === activeTabIndex ? "is-active" : ""
              }`}
            >
              {tab.name}
            </div>
          )
        })}
      </div>
    </TabNavigationStyleComponent>
  )
}

TabNavigation.defaultProps = {
  activeTabIndex: 0,
  tabWidth: 120,
  onSelectTab: (s) => s,
  tabs: [{ name: "no-tab", key: "no-tab" }],
  forceMount: false
}
