// @flow
import React, { useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import randomstring from 'randomstring';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';

import { RadioButton } from '.';
import { Box } from '../../../primitives/box';
import { withDocs } from '../../../../.storybook/with-docs';
import docs from './RADIO_BUTTON.mkd';

const _RadioButtonDemo = ({
  identifiers,
  demoSelectedIdentifier,
  onDemoSelectedValueChange,
}) => {
  const uniqueId = randomstring.generate(3);
  return (
    <Box>
      <fieldset id={`demo-${uniqueId}`}>
        {identifiers.map(identifier => (
          <RadioButton
            name={`demo-${uniqueId}`}
            id={identifier}
            key={identifier}
            text={`${identifier} - ${
              identifier === demoSelectedIdentifier
                ? 'I am the chosen one'
                : 'I am NOT the chosen one'
            }`}
            selected={identifier === demoSelectedIdentifier}
            onClick={onDemoSelectedValueChange}
          />
        ))}
      </fieldset>
    </Box>
  );
};

_RadioButtonDemo.propTypes = {
  identifiers: PropTypes.arrayOf(PropTypes.string),
  demoSelectedIdentifier: PropTypes.string,
  onDemoSelectedValueChange: PropTypes.func.isRequired,
};

const RadioButtonDemo = ({ identifiers }: { identifiers: Array<string> }) => {
  const [demoSelectedIdentifier, setDemoSelectedIdentifier] = useState('');

  const onDemoSelectedValueChange = useCallback(newSelectedIdentifier => {
    setDemoSelectedIdentifier(newSelectedIdentifier);
    action('option changed')(newSelectedIdentifier);
  }, []);

  return (
    <_RadioButtonDemo
      identifiers={identifiers}
      demoSelectedIdentifier={demoSelectedIdentifier}
      onDemoSelectedValueChange={onDemoSelectedValueChange}
    />
  );
};

const identifiers = [
  'radio-button-id-1',
  'radio-button-id-2',
  'radio-button-id-3',
  'radio-button-id-4',
];

storiesOf('Core/Forms/RadioButton', module).add(
  'normal',
  withDocs(docs)(() => <RadioButtonDemo identifiers={identifiers} />),
);
