import Tippy from '@tippyjs/react'
import type { JSXElementConstructor, ReactElement } from 'react'

import { cs } from '../utils'
import type { CloseEvent, TutorialProps } from './tutorial.types'
import { TutorialCard } from './tutorialCard'

/** Popover Tutorial is used to display information about a new, or existing feature. */
export function Tutorial({
  actionLabel,
  children,
  className,
  onAction,
  onDismiss,
  onFinish,
  steps,
  title,
  placement = 'right',
  showSkipButton,
  isVisible = true,
  includeFinalPage = true,
  useContentTitle = false,
}: TutorialProps) {
  const onClose = (e: CloseEvent) => {
    if (e === 'dismissed') onDismiss?.()
    if (e === 'finished') onFinish?.()
  }

  return (
    <Tippy
      content={
        <TutorialCard
          actionLabel={actionLabel}
          className={cs('vui-tutorial', className)}
          onAction={onAction}
          onDismiss={() => onClose('dismissed')}
          onFinish={() => onClose('finished')}
          showSkipButton={showSkipButton}
          steps={steps}
          title={title}
          includeFinalPage={includeFinalPage}
          useContentTitle={useContentTitle}
        />
      }
      interactive
      offset={[0, 2]}
      placement={placement}
      popperOptions={{
        modifiers: [
          {
            name: 'flip',
            enabled: false,
          },
        ],
      }}
      visible={isVisible}
    >
      {children as ReactElement<any, string | JSXElementConstructor<any>> | undefined}
    </Tippy>
  )
}

Tutorial.displayName = 'Tutorial'
