import * as React from 'react'
import { ShortenedContent, Content, OptionsGroupContainer, RadioInput } from './styles'
import { Size } from './Size'

type Value = string | number

type OptionItem = {
  value: Value
  label: Value
}

export type RenderLabelParams = {
  size: Size
  label: string
}

type ToggleButtonGroupProps = {
  items: OptionItem[]
  value?: Value
  onChange: (value: string) => void
  renderLabel?: (params: RenderLabelParams) => React.ReactNode
  size?: Size
}

export class ToggleButtonGroup extends React.Component<ToggleButtonGroupProps> {
  static ShortenedContent = ShortenedContent

  static defaultProps = {
    size: Size.REGULAR,
    renderLabel: ({ size, label }: RenderLabelParams) => (
      <Content size={size}>{label}</Content>
    ),
  }

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

  render() {
    const { items, value, size, renderLabel } = this.props

    return (
      <OptionsGroupContainer>
        {items.map(item => {
          const label = item.label.toString()
          // @ts-ignore
          const renderedLabel = renderLabel({ size, label })
          return (
            <label key={item.value} title={label}>
              <RadioInput
                onChange={this.onChange}
                type="radio"
                value={item.value}
                checked={item.value === value}
              />
              {renderedLabel}
            </label>
          )
        })}
      </OptionsGroupContainer>
    )
  }
}

export { Size } from './Size'
