import Modal from 'components/Modal'
import React, { useCallback } from 'react'
import { SHOPIFY_STORE_DOMAIN } from 'constants/regexp'
import { isMobile } from 'react-device-detect'
import Tooltip from 'antd/lib/tooltip'
import { Text } from 'components/Typography'
import { Icon } from 'components/Icon'
import { Button, Form, Input, Row } from 'antd'
import { useForm } from 'antd/lib/form/Form'
import { ryeShopifyService } from 'services'
import notification from 'utils/notification'
import { useTypedSelector } from 'redux/rootReducer'
import PopupWindow from 'components/PopupWindowRyeShopifyAuth'
import { selectRyeShopifyStores } from 'redux/RyeShopify/selector'
import { setRyeShopifyStoreAction } from 'redux/RyeShopify/actions'
import { selectTalentProfile } from 'redux/User/selector'
import { useDispatch } from 'react-redux'
import './index.scss'
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'

interface ConnectShopifyModalProps {
  toggleModal: (value: boolean) => void
  callback?: () => void
  caller: 'Modules page' | 'Profile settings'
}

const RyeShopifyStoreDomainInputModal = ({
  toggleModal,
  callback,
  caller
}: ConnectShopifyModalProps) => {
  const dispatch = useDispatch()
  const [form] = useForm()

  const stores = useTypedSelector(selectRyeShopifyStores)
  const talentProfile = useTypedSelector(selectTalentProfile)
  const talentProfileId = talentProfile?.id
  const { sendSegmentEvent } = useAnalytics()
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const shopifyConnectionFlowCompleted = createTracker(
    CreatorEvent.SHOPIFY_CONNECTION_FLOW_COMPLETED
  )

  const createAndSetRyeShopifyStore = async (
    talentProfileId: string,
    storeDomain: string
  ): Promise<boolean> => {
    const isCreated = await ryeShopifyService().createRyeStore(
      talentProfileId,
      storeDomain
    )
    if (isCreated) {
      dispatch(
        setRyeShopifyStoreAction([
          ...stores,
          {
            name: storeDomain,
            domain: storeDomain,
            connected: true
          }
        ])
      )
    }
    return isCreated
  }

  const handleOpenLoginPage = async () => {
    const storeDomain: string = form.getFieldValue('storeDomain')
    // Case 1: if shopify store already exist
    const isStoreAdded = stores.some(store => store.domain === storeDomain)
    if (isStoreAdded) {
      notification.error({
        message: 'This store is already added'
      })
      toggleModal(false)
      return
    }

    if (!talentProfileId) {
      notification.error({
        message: 'Something went wrong with Shopify service.'
      })
      toggleModal(false)
      return
    }

    const resolverCallback = async () => {
      return await ryeShopifyService().checkIfAppInstalled(storeDomain)
    }
    const popup = PopupWindow.open(
      'rye-shopify-app-installation',
      '',
      {
        height: 600,
        width: 1000
      },
      resolverCallback
    )

    // Case 2: if Rye app is installed but the store is not added
    const isRyeAppInstalled =
      await ryeShopifyService().checkIfAppInstalled(storeDomain)
    if (isRyeAppInstalled) {
      const isCreated = await createAndSetRyeShopifyStore(
        talentProfileId,
        storeDomain
      )
      if (isCreated) {
        callback && callback()
      } else {
        notification.error({
          message: 'Something went wrong with Shopify service'
        })
      }
      toggleModal(false)
      popup.close()
      return
    }

    // Case 3: if Rye app needs to be installed first
    const redirectLinkResponse =
      await ryeShopifyService().generateRyeShopifyAppInstalLink(storeDomain)
    if (!redirectLinkResponse || !redirectLinkResponse.ok) {
      notification.error({
        message: 'Something went wrong with Shopify service.'
      })

      popup.close()
      return
    }

    popup.navigate(redirectLinkResponse.response)

    const handlePopupFailedExit = (_error: any) => {
      notification.error({
        message:
          'Your Shopify connection was unsuccessful. Please try connecting again to start adding products from your Shopify store.'
      })

      const success = false
      const from = caller
      const count = stores?.length ?? 0

      useAnalyticsSDK
        ? shopifyConnectionFlowCompleted({
            from,
            stores: count,
            success
          })
        : sendSegmentEvent(SEGMENT_EVENTS.SHOPIFY_CONNECTION_FLOW_COMPLETED, {
            'Number of connected stores': count,
            'Added from': from,
            'Is successful': success
          })
    }

    const handlePopupOnSuccessExit = async () => {
      const [isRyeAppInstalled, ryeStores] = await Promise.all([
        ryeShopifyService().checkIfAppInstalled(storeDomain),
        ryeShopifyService().getRyeStores(talentProfileId)
      ])

      const connectedStoreDomains = ryeStores.map(store => store.shop)
      const isStoreAdded = connectedStoreDomains.includes(storeDomain)

      if (isRyeAppInstalled && !isStoreAdded) {
        const isCreated = await createAndSetRyeShopifyStore(
          talentProfileId,
          storeDomain
        )

        if (isCreated) {
          callback && callback()
          return
        }
      }

      handlePopupFailedExit(undefined)

      return
    }

    popup.then(
      () => handlePopupOnSuccessExit(),
      (error: any) => handlePopupFailedExit(error)
    )

    toggleModal(false)
  }

  const handleSubmit = useCallback(() => {
    form.validateFields().then(() => {
      handleOpenLoginPage()
    })
  }, [form])

  return (
    <Modal
      closable
      centered
      className="store-domain-input-modal"
      visible
      title="Connect Shopify"
      onCancel={() => toggleModal(false)}
      width={664}
    >
      <Row align="middle" className="m__b--16">
        <Text preset="semibold18">What is your Shopify URL?</Text>
        <Tooltip
          className="align__self--center"
          overlayClassName="store-domain-input-modal__tooltip"
          placement={isMobile ? 'bottom' : 'bottomLeft'}
          title="Your Shopify store URL will be in the format  [your-shop-name].myshopify.com.
          If you can’t remember your shop URL you can find it by logging into your Shopify admin."
          color={'#000'}
        >
          <div className="height--24 width--24 m__l--8">
            <Icon name="question" />
          </div>
        </Tooltip>
      </Row>
      <Row className="m__b--8">
        <Text preset="regular14">Store domain</Text>
      </Row>
      <Form
        onFieldsChange={fields => {
          const url = fields[0].value
            ?.replace(/(^\w+:|^)\/\//, '')
            .replace('/', '')
          form.setFieldsValue({ storeDomain: url })
        }}
        form={form}
        onFinish={handleSubmit}
      >
        <Form.Item
          rules={[
            {
              required: true,
              message: 'Please enter this field'
            },
            {
              pattern: SHOPIFY_STORE_DOMAIN,
              message: 'Please enter a valid Shopify store link',
              validateTrigger: 'onSubmit'
            }
          ]}
          name="storeDomain"
        >
          <Input autoFocus placeholder="store.myshopify.com" />
        </Form.Item>
        <Form.Item className="m__b--16">
          <Button
            className="text__transform--uppercase letter__spacing--1"
            type="primary"
            size="large"
            htmlType="submit"
            block
          >
            Continue to Shopify
          </Button>
        </Form.Item>
      </Form>

      <Row className="m__t--16">
        <Text preset="regular14">
          A Shopify login window will appear and you’ll be prompted to enter the
          username and password for your store. Once you are logged in, you’ll
          be redirected back to Komi.
        </Text>
      </Row>
    </Modal>
  )
}

export default RyeShopifyStoreDomainInputModal
