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

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

/** Popover Tutorial is used to display information about a new, or existing feature. */
export function Tutorial({
  actionLabel,
  children,
  className,
  onAction,
  onDismiss,
  onFinish,
  steps,
  title,
  id,
  placement = 'right',
  showSkipButton,
}: TutorialProps) {
  const { isVisible, setIsVisible, saveDisplayed } = useTutorial(id)

  const onClose = (e: CloseEvent) => {
    setIsVisible(false)
    if (e === 'dismissed') onDismiss?.()
    if (e === 'finished') onFinish?.()
    saveDisplayed(e)
  }

  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}
        />
      }
      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'
