// @flow
import React, { useState, useCallback, useMemo } from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { ToastCentre } from './index';
import { Box, Button } from '../../../..';
import { withDocs } from '../../../../../.storybook/with-docs';
import docs from './TOAST_CENTRE.mkd';
import { Toast } from '../toast';

const TOAST_MESSAGES = [
  { message: 'first' },
  { message: 'second', level: 'info' },
  { message: 'third', level: 'success' },
  { message: 'fourth', level: 'error' },
];

const ToastCentreDemo = () => {
  const [messages, setMessages] = useState([]);
  const toastMessages = useMemo(
    () =>
      TOAST_MESSAGES.map(({ message, ...other }) => ({
        id: `toast-${message}`,
        text: `I am the ${message} toast`,
        onClose: action(`closing the ${message} toast`),
        ...other,
      })),
    [],
  );

  const makeToast = useCallback(() => {
    setMessages(toastMessages);
  }, [toastMessages]);

  return (
    <>
      <Box spacing={['p2']}>
        <Button onClick={makeToast}>Make toast</Button>
      </Box>

      <ToastCentre messages={messages} />
    </>
  );
};

ToastCentreDemo.displayName = 'ToastCentreDemo';

const ToastCentreWithCustomDelay = () => {
  const [messages, setMessages] = useState([]);
  const toastMessages = useMemo(
    () =>
      TOAST_MESSAGES.map(({ message, ...other }, index) => ({
        id: `toast-${message}`,
        text: `I am the ${message} toast`,
        timerDelay: index * 1000,
        onClose: action(`closing the ${message} toast`),
        ...other,
      })),
    [],
  );

  const makeToast = useCallback(() => {
    setMessages(toastMessages);
  }, [toastMessages]);

  return (
    <>
      <Box spacing={['p2']}>
        <Button onClick={makeToast}>Make toast with custom delays</Button>
      </Box>

      <ToastCentre messages={messages} />
    </>
  );
};

storiesOf('Core/Overlays/Toast', module)
  .add(
    'ToastCentre',
    withDocs(docs, [ToastCentreDemo], [ToastCentre, Toast])(() => (
      <ToastCentreDemo />
    )),
  )
  .add(
    'ToastCentre with custom delay',
    withDocs(docs, [ToastCentreDemo], [ToastCentre, Toast])(() => (
      <ToastCentreWithCustomDelay />
    )),
  );
