// @flow
import React, { useState, useCallback, useMemo } from 'react';

import randomstring from 'randomstring';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withInfo } from '@storybook/addon-info';

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

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

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

  const uniqueId = useMemo(() => 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>
  );
};

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

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