// @flow
import React, { useState, useCallback, useRef } from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { CheckboxStandalone } from '.';

const Demo = () => {
  const [c1, setC1] = useState(false);
  const [c2, setC2] = useState(false);
  const formRef = useRef();
  const validity = formRef.current ? formRef.current.checkValidity() : false;

  const handleC1Click = useCallback(() => {
    const newState = !c1;
    action('Setting c1')(newState);
    setC1(newState);
  }, [c1]);

  const handleC2Click = useCallback(() => {
    const newState = !c2;
    action('Setting c2')(newState);
    setC2(newState);
  }, [c2]);

  return (
    <form ref={formRef}>
      <CheckboxStandalone
        label="Required"
        selected={c1}
        onClick={handleC1Click}
        required
      />
      <CheckboxStandalone
        label="Not Required"
        selected={c2}
        onClick={handleC2Click}
      />
      <div style={{ width: '200px' }}>
        <CheckboxStandalone
          label="Super duper long long long long long long long long long"
          selected={c1}
          onClick={handleC1Click}
          required
        />
      </div>

      {validity ? 'Form is valid!' : 'Form is invalid!'}
    </form>
  );
};

const ToggleableCheckbox = (props) => {
  const [isChecked, setIsChecked] = useState(false);
  const toggleChecked = useCallback(() => {
    action('onClick')();
    setIsChecked(!isChecked);
  }, [isChecked]);

  return (
    <CheckboxStandalone
      selected={isChecked}
      onClick={toggleChecked}
      {...props}
    />
  );
};

storiesOf('Core/Forms/CheckboxStandalone', module)
  .add('normal', () => <Demo />)
  .add('enabled', () => <ToggleableCheckbox label="Enabled Checkbox" />)
  .add('disabled', () => (
    <ToggleableCheckbox label="Disabled Checkbox" disabled />
  ));
