import When from '@komi-app/when'
import ConfirmDeleteModal from 'components/ConfirmDeleteModal'
import { TemplatePublishWarningModal } from 'components/TemplatePublishWarningModal/TemplatePublishWarningModal'
import { useHasTemplates } from 'hooks/useHasTemplates'
import { selectUserData } from 'redux/User/selector'
import { useTypedSelector } from 'redux/rootReducer'
import { authService } from 'services'

interface PrePublishModalProps {
  show: boolean
  closeModal: () => void
  onPublish: () => void

  // Specific to email verification modal
  onResendLink?: () => void
}

/**
 * Effectively a meta-modal that can choose which publish modal to render based on profile state
 */
const PrePublishModal: React.FC<PrePublishModalProps> = ({
  show,
  closeModal,
  onPublish,
  onResendLink
}) => {
  const user = useTypedSelector(selectUserData)
  const emailVerified = user?.emailVerified || authService.emailVerified
  const hasTemplateModules = useHasTemplates()

  // Email not verified, show email verification modal instead
  if (!emailVerified) {
    return (
      <ConfirmDeleteModal
        show={show}
        reverse
        title="Your email hasn't been confirmed"
        description="You will be able to publish once you have clicked on your activation link. Then, your updates will be reflected on the live version of your page."
        confirmLabel="CONTINUE"
        cancelLabel="RESEND LINK"
        handleConfirm={onPublish}
        handleCancel={onResendLink}
        toggleModal={closeModal}
      />
    )
  }

  if (hasTemplateModules) {
    return (
      <When
        value={show}
        then={
          <TemplatePublishWarningModal
            onPublish={onPublish}
            onClose={closeModal}
          />
        }
      />
    )
  }

  return (
    <ConfirmDeleteModal
      show={show}
      reverse
      title="You are About to Publish Your Updated Profile"
      description="Once your updates are published, they will be reflected on the live version of your Komi page and everyone will be able to see them. Do you want to proceed?"
      confirmLabel="PUBLISH"
      cancelLabel="CANCEL"
      handleConfirm={onPublish}
      toggleModal={closeModal}
    />
  )
}

export default PrePublishModal
