import * as React from 'react'
import { StylableComponent } from '../theme'
import { Row } from '../flex'
import { RadioButton, RadioOption } from '../radio-button'
import { Divider } from '../divider'
import { RadioGroupProps } from './interfaces'

const styles = require('../../../src/components/form-field/styles.scss')

export class RadioGroup extends StylableComponent<RadioGroupProps> {

    public render() {
        const { formName, options } = this.props
        return (
            <Row justify="space-between">
                {options.map(o =>
                    <RadioButton
                        isSelected={this.isSelected(o)}
                        onChange={this.onChange(o.label)}
                        key={o.label}
                        name={formName}
                        label={o.label}
                        value={o}
                        img={o.img} />)}
            </Row>
        )
    }

    /**
     * Radio options have the exact same problem as select options
     * You can't set an object as a radio option's value, so inorder to get round this
     * you need to find the object by id and then pass that in as the value
     */
    private onChange = (id: string): any =>
        (e: React.SyntheticEvent<any>) => {
            const selected = this.props.options.find(o => o.label === id)
            this.props.onChange(selected)
        }

    private isSelected(option: RadioOption) {
        return this.props.selected && this.props.selected.label === option.label
    }
}
