import clsx from 'clsx'
import React, { FC, useMemo, useState } from 'react'

import { theming } from '../../themes'
import { useStyles } from './styles'

export type TabType = { key: string; label: string }

export type TabProps = {
  tabs: TabType[]
  activeTab: string
  onChange?: (index: string) => void
}

export const Tabs: FC<TabProps> = ({ tabs, activeTab = tabs[0].key, onChange }) => {
  const { tabsWrapper, tabButton, tabButtonActive } = useStyles({ theme: theming.useTheme() })

  const [currentTab, setCurrentTab] = useState(activeTab)

  const style = useMemo(() => ({ width: `calc(100% / ${tabs.length})` }), [tabs])

  const onSelectTab = (tabKey: string) => {
    setCurrentTab(tabKey)
    if (onChange) {
      onChange(currentTab)
    }
  }

  return (
    <div className={tabsWrapper}>
      {tabs.map((tab) => {
        return (
          <button
            key={tab.key}
            className={clsx(tabButton, tab.key === currentTab && tabButtonActive)}
            onClick={() => onSelectTab(tab.key)}
            style={style}
          >
            <p>{tab.label}</p>
          </button>
        )
      })}
    </div>
  )
}
