import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { fn, userEvent, within } from 'storybook/test';
import { wait } from '../test-utils/wait';
import Button from '../button';
import { Snackbar } from './Snackbar';
import { SnackbarConsumer } from './SnackbarContext';
import SnackbarProvider from './SnackbarProvider';

const meta: Meta = {
  component: Snackbar,
  title: 'Dialogs/Snackbar',
};
export default meta;

export const Basic: StoryObj = {
  parameters: {
    docs: {
      source: {
        type: 'code',
        transform: async (src = '') => {
          const match = /(function Render\(\).*?)(,\s+play:\s+async)/s.exec(src);
          return match?.[1] || src;
        },
      },
    },
    source: {
      type: 'code',
    },
  },
  render: function Render() {
    return (
      <SnackbarProvider>
        <SnackbarConsumer>
          {({ createSnackbar }) => {
            return (
              <Button
                block
                onClick={() => {
                  createSnackbar({
                    action: {
                      label: 'View',
                      onClick: fn(),
                    },
                    text: <span>Some text</span>,
                  });
                }}
              >
                Show Snackbar
              </Button>
            );
          }}
        </SnackbarConsumer>
      </SnackbarProvider>
    );
  },
  play: async ({ canvasElement }) => {
    await wait(0);
    const canvas = within(canvasElement);
    await userEvent.click(canvas.getByRole('button'));
  },
};
