import { Children, ReactElement } from 'react'
import { Text } from './text.js'
import styled from 'styled-components'
import { InferComponentProps } from './types.js'

export const TabGroupContainer = styled.nav`
  width: 100%;
  display: flex;
  flex-flow: row nowrap;
  border-bottom: 1px solid ${({ theme }) => theme.navNeutral200};
  padding-top: 16px;

  & > * {
    padding: 8px 0 16px;
    margin-right: 48px;
  }

  & > *:last-child {
    margin-right: 0;
  }

  button {
    border-bottom-width: 0;
    font-weight: 600;
  }
`

export const Tab = styled(Text).withConfig({
  shouldForwardProp: (prop) => !['isActive'].includes(prop),
})<{ isActive?: boolean }>`
  position: relative;
  color: ${({ theme, isActive }) => (isActive ? theme.navPrimary400 : theme.navNeutral400)};

  &:hover {
    color: ${({ theme }) => theme.navPrimary400};
  }

  &::after {
    content: '';
    width: 100%;
    height: 4px;
    background-color: ${({ isActive, theme }) => (isActive ? theme.navPrimary400 : 'transparent')};
    border-radius: 2px;
    position: absolute;
    bottom: 0;
    left: 0;
  }
`

type TabGroupProps = InferComponentProps<typeof TabGroupContainer> & {
  children?: ReactElement[]
}

export const TabGroup = ({ children, ...props }: TabGroupProps) => (
  <TabGroupContainer data-testid="tab-group" {...props}>
    {Children.toArray(children).map(({ type, key, props }: ReactElement) => (
      <Tab as={type} key={key} {...props} />
    ))}
  </TabGroupContainer>
)
