// @flow
import React, { useState, useRef, useCallback } from 'react';
import { action } from '@storybook/addon-actions';
import { CheckboxStandalone } from './checkbox-standalone.component';
import { MarginChecker } from '../../../mixins/spacing/story-support/margin-checker';
import { PaddingChecker } from '../../../mixins/spacing/story-support/padding-checker';
import { StackeeChecker } from '../../../mixins/stackee/story-support/stackee-checker';
import docs from './checkbox-standalone.mdx';

export default {
  component: CheckboxStandalone,
  title: 'Components/Inputs/CheckboxStandalone',
  parameters: {
    docs: {
      page: docs,
    },
  },
};

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>
  );
};

type ToggleableCheckboxProps = { disabled?: boolean, label: string };
const ToggleableCheckbox = ({
  label,
  disabled = false,
}: ToggleableCheckboxProps) => {
  const [isChecked, setIsChecked] = useState(false);
  const toggleChecked = useCallback(() => {
    action('onClick')();
    setIsChecked(!isChecked);
  }, [isChecked]);

  return (
    <CheckboxStandalone
      selected={isChecked}
      onClick={toggleChecked}
      label={label}
      disabled={disabled}
    />
  );
};

export const Demo = () => <_Demo />;
export const Enabled = () => <ToggleableCheckbox label="Enabled Checkbox" />;
export const Disabled = () => (
  <ToggleableCheckbox label="Disabled Checkbox" disabled />
);

export const MixinsMarginOnlySpacing = () => (
  <>
    <MarginChecker Component={CheckboxStandalone} label="check me" />
    <PaddingChecker Component={CheckboxStandalone} label="check me" />
  </>
);

export const MixinsStackee = () => (
  <StackeeChecker
    Component={CheckboxStandalone}
    label="very label. much wow. amaze."
  />
);
