import React, { useEffect, useState } from 'react'
import { Modal } from 'antd'
import classnames from 'classnames'
import { useSelector, useDispatch } from 'react-redux'

import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import classNames from 'classnames'

import { ReactComponent as MobileIcon } from '../../icons/mobile-blue.svg'
import { ReactComponent as MobileBusyIcon } from '../../icons/mobile-busy-blue.svg'

import Loading from '../Loading'
import { Paragraph, Title } from '../Typography'
import { useTypedSelector } from '../../redux/rootReducer'
import {
  selectTalentProfile,
  selectTalentProfileModules
} from '../../redux/User/selector'
import { UserProfile } from '../../redux/User/types'
import { setTalentProfileAction } from '../../redux/User/actions'

import { createTemplateForIndustry } from '../../services/profile-templates/TemplateService'

import { useAnalytics } from '../../hooks/useAnalytics'
import { SEGMENT_EVENTS } from '../../constants/segment'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'

import { useModules } from '../../hooks/useModules'

import './TemplateSelectionModal.scss'

interface TemplateSelectionModalProps {
  onStartFromScratch?: () => void
}

export function TemplateSelectionModal({
  onStartFromScratch
}: TemplateSelectionModalProps) {
  const { sendSegmentEvent } = useAnalytics()
  const { modules } = useModules()
  const talentProfile = useTypedSelector(selectTalentProfile)
  const talentProfileModules = useSelector(selectTalentProfileModules)
  const {
    displayName,
    id: talentProfileId,
    category,
    user,
    socialProfileLinks,
    avatar
  } = talentProfile || {}

  const [loading, setLoading] = useState<boolean>(false)
  const [visible, setVisible] = useState<boolean | undefined>(undefined)

  const isAlignmentFixOn = useFeatureIsOn(
    FLAGS.FEAT_SB_353_TEMPLATE_BUTTON_VERTICAL
  )

  const isContentMenuOn = useFeatureIsOn(FLAGS.FEAT_SB_389_ADD_ITEM_MENU)
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const viewTemplateSelectionModal = createTracker(
    CreatorEvent.VIEW_TEMPLATE_SELECTION_MODAL
  )
  const clickBlankTemplate = createTracker(CreatorEvent.CLICK_BLANK_TEMPLATE)
  const clickPopulatedTemplate = createTracker(
    CreatorEvent.CLICK_POPULATED_TEMPLATE
  )

  const { replaceSocialLinks, replaceModules, replaceAvatar } =
    useTalentProfileUpdater()

  useEffect(() => {
    if (visible) {
      useAnalyticsSDK
        ? viewTemplateSelectionModal()
        : sendSegmentEvent(SEGMENT_EVENTS.VIEW_TEMPLATE_SELECTION_MODAL)
    }
  }, [visible])

  useEffect(() => {
    if (visible !== undefined) {
      return // only show modal on load
    }

    if (!talentProfileModules) {
      return // don't show before profile is loaded
    }

    const hasModules = !!modules.length
    if (!hasModules) {
      setVisible(true)
    } else {
      setVisible(false)
    }
  }, [talentProfileModules, socialProfileLinks, avatar, visible, modules])

  function closeModal() {
    if (isContentMenuOn) {
      setVisible(false)
    }
  }

  async function loadTemplate() {
    setLoading(true)

    // if (!displayName || !talentProfileId || !user?.id) { // TODO: explain what this condition means/why is it there?
    if (!talentProfileId || !user?.id) {
      return
    }

    const template = createTemplateForIndustry(category?.name)

    const hasAvatar = !!avatar
    if (!hasAvatar) {
      replaceAvatar(template.avatar)
    }

    const hasSocialLinks = !!socialProfileLinks?.length
    if (!hasSocialLinks) {
      replaceSocialLinks(template.socialProfileLinks)
    }

    const hasModules = !!modules.length
    if (!hasModules) {
      replaceModules(template.modules)
    }

    setLoading(false)
    setVisible(false)
  }

  const onClickFromScratch = () => {
    useAnalyticsSDK
      ? clickBlankTemplate()
      : sendSegmentEvent(SEGMENT_EVENTS.CLICK_BLANK_TEMPLATE)
    setVisible(false)
    onStartFromScratch?.()
  }

  const onClickUseTemplate = () => {
    useAnalyticsSDK
      ? clickPopulatedTemplate()
      : sendSegmentEvent(SEGMENT_EVENTS.CLICK_POPULATED_TEMPLATE)
    loadTemplate()
  }

  return (
    <Modal
      visible={visible}
      centered
      closable={false}
      onCancel={closeModal}
      footer={null}
    >
      {loading && (
        <Loading
          size="large"
          blur
          className="border__radius--16"
          data-testid="loading"
        />
      )}
      <Title preset="semibold20">Creating your profile</Title>
      <div
        className={classNames('flex justify-between m__t--24', {
          'template-selection-container': isAlignmentFixOn
        })}
      >
        <TemplateButton
          title="Start from scratch"
          description="Jump right in and building something beautiful"
          icon={<MobileIcon />}
          onClick={onClickFromScratch}
        />
        <TemplateButton
          title="Use a template"
          description="Save time and create your page faster"
          icon={<MobileBusyIcon />}
          className={classNames({ 'm__l--24': !isAlignmentFixOn })}
          onClick={onClickUseTemplate}
        />
      </div>
    </Modal>
  )
}

function TemplateButton({
  title,
  description,
  onClick,
  className: classNameProp,
  icon
}: any) {
  const className = classnames(
    'full-width p__16 border__solid--grey200 bo__radius--8 p--16 clickable',
    classNameProp
  )
  return (
    <div role="button" onClick={onClick} className={className}>
      {icon}
      <Title level={2} preset="semibold16">
        {title}
      </Title>
      <Paragraph
        className="text--tundola"
        preset="regular14"
        style={{ lineHeight: '21px' }}
      >
        {description}
      </Paragraph>
    </div>
  )
}

const setTalentProfileActionTyped = (payload: Partial<UserProfile>) =>
  setTalentProfileAction(payload)

function useTalentProfileUpdater() {
  const dispatch = useDispatch()
  const { setModuleList } = useModules()

  const replaceSocialLinks = (
    socialProfileLinks: UserProfile['socialProfileLinks']
  ) => {
    dispatch(setTalentProfileActionTyped({ socialProfileLinks }))
  }

  const replaceModules = (modules: UserProfile['modules']) => {
    if (modules && setModuleList) {
      setModuleList(modules)
    }
  }

  const replaceAvatar = (avatar: UserProfile['avatar']) => {
    dispatch(setTalentProfileActionTyped({ avatar }))
  }

  return {
    replaceSocialLinks,
    replaceModules,
    replaceAvatar
  }
}
