import React from 'react';
import PropTypes from 'prop-types';
import {Button} from '../../Button';
import {Block} from '../../Block';

let instanceCounter = 0;

export class TimeAmPmEditor extends React.PureComponent {
    static propTypes = {
        isAm: PropTypes.bool.isRequired,
        onAmPmChange: PropTypes.func.isRequired,
        amLabel: PropTypes.string.isRequired,
        pmLabel: PropTypes.string.isRequired,
        amPmSwitcherLabel: PropTypes.string.isRequired,
        enablePMTitle: PropTypes.string.isRequired,
        enableAMTitle: PropTypes.string.isRequired
    };

    constructor(props, ctx) {
        super(props, ctx);
        this.instanceId = instanceCounter++;
    }

    handleToggleAmPM = () => {
        const {isAm, onAmPmChange} = this.props;
        onAmPmChange(!isAm);
    };

    getTitle = () => {
        const {isAm, enableAMTitle, enablePMTitle} = this.props;

        return isAm ? enablePMTitle : enableAMTitle;
    };

    render() {
        const {isAm, amPmSwitcherLabel, amLabel, pmLabel} = this.props;
        const descriptionId = `amPmSwitcherDescription-${this.instanceId}`;

        return (
            <Block className="rc-datepicker-am-pm-button" testAutomationId="amPmSwitcher">
                <p className="sr-only" id={descriptionId}>
                    {this.getTitle()}
                </p>
                <div className="text-center time-text">
                    <Button
                        testAutomationId="amPmSwitchButton"
                        onClick={this.handleToggleAmPM}
                        bsStyle="primary"
                        aria-label={amPmSwitcherLabel}
                        title={this.getTitle()}
                        aria-describedby={descriptionId}>
                        {isAm ? amLabel : pmLabel}
                    </Button>
                </div>
            </Block>
        );
    }
}
