// @flow
import React, { useState, useCallback } from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { Button } from '../../actions/button';
import { Grid, GridItem } from '../../structures';
import { withDocs } from '../../../../.storybook/with-docs';
import { CurrencyInput } from '.';
import docs from './CURRENCY_INPUT.mkd';

type DemoProps = {|
  defaultValue?: number,
  placeholder?: number,
  large?: boolean,
  showValueUpdateButton?: boolean,
|};
const Demo = ({
  defaultValue,
  placeholder,
  large = false,
  showValueUpdateButton = false,
}: DemoProps) => {
  const [amount, setAmount] = useState(defaultValue);
  const handleAmountChanged = useCallback(newAmount => {
    setAmount(newAmount);
    action('Setting amount')(newAmount);
  }, []);

  const setValue = useCallback(() => {
    handleAmountChanged(123.45);
  }, [handleAmountChanged]);

  return (
    <>
      {showValueUpdateButton && (
        <Button onClick={setValue}>Set amount to 123.45</Button>
      )}
      <CurrencyInput
        label="Amount"
        currency="CAD"
        onChange={handleAmountChanged}
        value={amount}
        placeholder={placeholder}
        large={large}
      />
    </>
  );
};

storiesOf('Core/Forms/CurrencyInput', module)
  .addDecorator(story => (
    <Grid>
      <GridItem sm={12} md={6} lg={4}>
        {story()}
      </GridItem>
    </Grid>
  ))
  .add(
    'normal',
    withDocs(docs, [Demo, GridItem, Grid])(() => <Demo defaultValue={1000} />),
  )
  .add(
    'without value',
    withDocs(docs, [Demo, GridItem, Grid])(() => <Demo placeholder={1000} />),
  )
  .add(
    'with externally updated value',
    withDocs(docs, [Demo, GridItem, Grid])(() => (
      <Demo defaultValue={500} showValueUpdateButton />
    )),
  )
  .add(
    'large',
    withDocs(docs, [Demo, GridItem, Grid])(() => (
      <Demo defaultValue={500} large />
    )),
  );
