import { toast } from './index.tsx'
import { Toast } from './Toast.tsx'

import type { Meta, StoryObj } from '@storybook/nextjs-vite'

import { config } from './variants.ts'
import { ToastHandler } from './ToastHandler.tsx'
import { Button } from '../Button/Button.tsx'
import { expect, waitFor } from 'storybook/test'

const meta: Meta<typeof Toast> = {
  title: 'Components/Toasts/ToastHandler',
  component: Toast,
  argTypes: {
    variant: {
      control: 'select',
      type: 'string',
      options: Object.keys(config.variants.variant),
      table: {
        defaultValue: { summary: 'info' },
      },
    },
    message: {
      control: 'text',
      type: 'string',
      table: {
        defaultValue: { summary: 'Toast message' },
      },
    },
  },
}

export default meta

type Story = StoryObj<typeof Toast>

export const Default: Story = {
  args: {
    variant: 'info',
    message: 'This is a toast',
  },
  render: (args) => {
    return <Renderer variant={args.variant} message={args.message as string} />
  },

  play: async ({ canvas, userEvent, args }) => {
    let toast = canvas.queryByRole('status')
    expect(toast).not.toBeInTheDocument()

    const showToastButton = await canvas.findByRole('button')
    await userEvent.click(showToastButton)

    toast = await canvas.findByRole(
      ['info', 'success'].indexOf(args.variant) !== -1 ? 'status' : 'alert'
    )
    await waitFor(async () => await expect(toast).toBeVisible())

    const closeButton = await canvas.findByLabelText('Dismiss notification')
    await userEvent.click(closeButton)

    await waitFor(async () => await expect(toast).not.toBeVisible())
  },
}

const Renderer = ({
  message,
  variant,
}: {
  message: string
  variant: 'info' | 'success' | 'warning' | 'error'
  onDismiss?: () => void
}) => {
  const text = 'Show Toast'
  return (
    <>
      <Button
        variant="Primary"
        onPress={() => {
          toast[variant](message)
        }}
      >
        {text}
      </Button>
      <ToastHandler />
    </>
  )
}
