import React, { useEffect } from 'react'
import selfless from '@komi-app/selfless'
import When from '@komi-app/when'
import {
  ButtonGroupOrientation,
  ButtonProps,
  ModalPropsWithChildren,
  ModalType,
  Semantic,
  useIsMobile,
  useModal
} from '@komi-app/creator-ui'
import { useAnalytics } from 'hooks/useAnalytics'
import { SEGMENT_EVENTS } from 'constants/segment'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'

export interface TemplatePublishWarningModalProps {
  onPublish: () => void
  onClose: () => void
}

interface ViewProps {
  showModal: boolean
  Modal: React.JSXElementConstructor<ModalPropsWithChildren>
  buttons: ButtonProps[]
  buttonOrientation?: ButtonGroupOrientation
}

const useTemplatePublishWarningModal = ({
  onPublish,
  onClose
}: TemplatePublishWarningModalProps): ViewProps => {
  const { Modal, openModal } = useModal()
  const { sendSegmentEvent } = useAnalytics()

  useEffect(() => {
    openModal()
  }, [])

  const isMobile = useIsMobile()
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const clickTemplateWarningBackToEditing = createTracker(
    CreatorEvent.CLICK_TEMPLATE_WARNING_BACK_TO_EDITING
  )
  const clickBypassTemplateWarning = createTracker(
    CreatorEvent.CLICK_BYPASS_TEMPLATE_WARNING
  )

  const buttons: ButtonProps[] = [
    {
      label: 'Back To Editing',
      semantic: Semantic.PRIMARY,
      onClick: () => {
        useAnalyticsSDK
          ? clickTemplateWarningBackToEditing()
          : sendSegmentEvent(
              SEGMENT_EVENTS.CLICK_TEMPLATE_WARNING_BACK_TO_EDITING
            )
        onClose()
      }
    },
    {
      label: 'Publish Anyway',
      semantic: Semantic.TERTIARY,
      onClick: () => {
        useAnalyticsSDK
          ? clickBypassTemplateWarning()
          : sendSegmentEvent(SEGMENT_EVENTS.CLICK_BYPASS_TEMPLATE_WARNING)
        onClose()
        onPublish()
      }
    }
  ]

  return {
    Modal,
    showModal: true,
    buttons,
    buttonOrientation: isMobile ? 'vertical' : 'horizontal'
  }
}

const View = ({ showModal, Modal, buttons, buttonOrientation }: ViewProps) => (
  <When
    value={showModal}
    then={
      <Modal
        heading="Your page is using templates"
        body="Make sure you’re using your content"
        type={ModalType.BASIC}
        buttons={buttons}
        buttonOrientation={buttonOrientation}
        dismissible={false}
      />
    }
  />
)

export const TemplatePublishWarningModal = selfless(
  View,
  useTemplatePublishWarningModal
)
