import { Fragment } from 'react'
import styled from 'styled-components/macro'

import map from 'lodash/map'

import type { ENVType } from 'config/env'
import { APIS } from 'config/routes'

import { RadioGroup, RadioButton } from '../RadioButtons'

import { SettingsDescription } from '../../styled'

const Details = styled.span`
  margin-top: 4px;
  font-size: 10px;
  text-transform: initial;
`

const getHost = (url: string) => new URL(url).host

type Option = {
  details: string,
  key: ENVType,
  label: string,
}

const options: Array<Option> = [
  {
    details: getHost(APIS.staging.api),
    key: 'staging',
    label: 'STAGE-OLD',
  },
  {
    details: getHost(APIS.preproduction.api),
    key: 'preproduction',
    label: 'STAGE-AWS',
  },
  {
    details: getHost(APIS.production.api),
    key: 'production',
    label: 'PRODUCTION',
  },
]

type Props = {
  onChange?: (value: ENVType) => void,
  selectedApi: ENVType,
}

export const APISettings = ({ onChange, selectedApi }: Props) => (
  <Fragment>
    <SettingsDescription>Подключенный API</SettingsDescription>
    <RadioGroup>
      {
        map(options, (option) => (
          <RadioButton
            key={option.key}
            name='api'
            onChange={onChange}
            value={option.key}
            defaultChecked={option.key === selectedApi}
          >
            {option.label}
            <Details>{option.details.replace('.instat.tv', '')}</Details>
          </RadioButton>
        ))
      }
    </RadioGroup>
  </Fragment>
)
