import { Alert, Col, Row } from 'antd'
import classNames from 'classnames'
import DragDropContext from 'components/DragDropContext'
import LoadingModule from 'components/LoadingModule'
import PortalComponent from 'components/PortalComponent/PortalComponent'
import ShopMySelfProductCard from 'components/ShopMySelfProductCard'
import ShopMyShelfEditorModal from 'components/ShopMyShelfEditorModal'
import { Text } from 'components/Typography'
import { SEGMENT_EVENTS } from 'constants/segment'
import { useAnalytics } from 'hooks/useAnalytics'
import { useModules } from 'hooks/useModules'
import {
  ShopMyShelfItem,
  TalentProfileModule
} from 'models/talent/talent-profile-module.model'
import React, { useCallback, useMemo, useState } from 'react'
import { DraggableProvidedDragHandleProps } from 'react-beautiful-dnd'
import { useTypedSelector } from 'redux/rootReducer'
import { selectLocalizationSelected } from 'redux/User/selector'
import { ArrayServices } from 'utils/array'
import { Icon } from '../../../components/Icon'
import { Paragraph } from '../../../components/Typography'
import ModuleEditor from '../ModuleEditor'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'
import { trackingProps } from 'utils/tracking'
import { useAnalyticsCompleteItemCreation } from 'hooks/useAnalyticsCompleteItemCreation'

const ShopMySelfProductCardMemo = React.memo(ShopMySelfProductCard)

interface ModuleShopMyShelfProps {
  module: TalentProfileModule<ShopMyShelfItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleShopMyShelf: React.FC<ModuleShopMyShelfProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const { sendSegmentEvent } = useAnalytics()
  const profileContext = useModules()
  const localizationSelected = useTypedSelector(selectLocalizationSelected)
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED)
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

  const item = useMemo(() => {
    return module.items[0]
  }, [module.items])
  const [showModal, setShowModal] = useState(false)
  const { loadingShop, thirdPartyData } = profileContext
  const loading = useMemo(() => {
    return loadingShop.some((key: string) => key === module.id)
  }, [loadingShop, module.id])
  const data = useMemo(() => {
    return thirdPartyData.find((item: any) => item.id === module.id)
  }, [thirdPartyData, module.id])
  const products = useMemo(() => data?.products || [], [data])

  const error = useMemo(() => {
    if (!data || data?.status === 'success') {
      return undefined
    }
    return data.status
  }, [data])

  const onEditModuleCallback = useCallback(
    (moduleEdit: TalentProfileModule<ShopMyShelfItem>) => {
      profileContext.setModule(moduleEdit)
    },
    [profileContext.setModule]
  )
  const onEditModuleLink = useCallback(() => {
    setShowModal(true)
  }, [])

  const onSaveLinkCallback = useCallback(
    data => {
      const moduleEdit = {
        ...module,
        name: data.name || module.name,
        items: ArrayServices.updateWithIndex(module.items, 0, {
          url: data.url,
          order: 0
        }),
        isUpdate: true
      }
      profileContext.setModule(moduleEdit)
      trackCompleteAddingItemToModule(moduleEdit)
      const { pageId, pageName, type } = trackingProps(
        moduleEdit.type,
        localizationSelected
      )

      useAnalyticsSDK
        ? elementCreate({ pageId, pageName, type })
        : sendSegmentEvent(SEGMENT_EVENTS.ELEMENT_CREATED, {
            'Module Type': moduleEdit.type,
            'Page ID': localizationSelected?.id || null,
            'Page Name': localizationSelected?.name || 'Default'
          })
      onToggleModal(false)
    },
    [module, localizationSelected, profileContext.setModule]
  )

  const onDropEndLinks = useCallback(
    (list: ShopMyShelfItem[]) => {
      onEditModuleCallback({
        ...module,
        items: list.map((item, index) => ({ ...item, order: index })),
        isUpdate: true
      })
    },
    [module, onEditModuleCallback]
  )

  const onToggleModal = useCallback((value: boolean) => {
    setShowModal(value)
  }, [])

  const errorMessage = useMemo(() => {
    if (error === 'cannot-connect') {
      return (
        <div>
          <div>
            Connection with Shop My could not be established at this time. Try
            reloading the page or check back later.
          </div>
          <div className="m__t--12">
            If there is an issue with Shop My, this module will be hidden from
            your profile until the connection is reestablished. The rest of your
            profile will not be affected and you can continue making and
            publishing changes as normal.
          </div>
        </div>
      )
    }
    return 'This Shop My collection no longer exists. Please add a new collection link to display products again.'
  }, [error])
  const renderContent = () => {
    if (loading) {
      return <LoadingModule />
    }
    if (!products.length) {
      return (
        <React.Fragment>
          {!!error && (
            <Alert
              className={classNames('warning-alert align__items--start', {
                'm__b--20': error !== 'cannot-connect'
              })}
              message={errorMessage}
              type="warning"
              icon={<Icon name="warning" />}
              closeText={<Icon width={24} height={24} name="close-outline" />}
              showIcon
              closable
            />
          )}
          {error !== 'cannot-connect' && (
            <Row justify="center">
              <Col span={24} className="text__align--center">
                <Icon name="empty-module" />
              </Col>
              <Col span={24} className="text__align--center max-w-393">
                <Paragraph preset="semibold18" className="d--block m__b--4">
                  No Products Found
                </Paragraph>
                <Paragraph preset="regular14" className="d--block text--grey4">
                  {error === 'not-found'
                    ? `It appears that your linked Shop My collection no longer exists. Try adding another collection link to display products again.`
                    : `It appears that you have no products in this Shop My
                  collection right now. Try adding products on your Shop My
                  Shelf page or edit your collection link.`}
                </Paragraph>
              </Col>
            </Row>
          )}
        </React.Fragment>
      )
    }

    return (
      <React.Fragment>
        <div className="d--flex justify__content--end align__items--center m__b--22">
          <Text preset="medium14" className="opacity-6">
            {products.length} {products.length > 1 ? 'products' : 'product'}
          </Text>
        </div>
        <DragDropContext
          droppableId="link-child-drop"
          listClassName="product-list"
          itemIdPrefix="link"
          direction="vertical"
          list={products}
          onDropEndCallback={onDropEndLinks}
        >
          {(dragProvided, snapshot, item, linkIndex) => {
            const isRender = active ? active : linkIndex < 2
            return isRender ? (
              <PortalComponent
                key={linkIndex}
                innerRef={dragProvided.innerRef}
                namespaceClass="product-list"
                provided={dragProvided}
                snapshot={snapshot}
                single={products?.length === 1}
              >
                <ShopMySelfProductCardMemo
                  index={linkIndex}
                  titleShortcut
                  item={item as any}
                  dragHandleProps={dragProvided.dragHandleProps}
                />
              </PortalComponent>
            ) : (
              <></>
            )
          }}
        </DragDropContext>
        {!active && products.length > 2 && (
          <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
            <Text preset="medium14" className="opacity-6">
              +{products.length - 2} More
            </Text>
          </div>
        )}
      </React.Fragment>
    )
  }

  return (
    <React.Fragment>
      <ModuleEditor
        module={module}
        dragHandleProps={dragHandleProps}
        onEditShopMyShelf={onEditModuleLink}
      >
        <ShopMyShelfEditorModal
          isEdit={true}
          item={item}
          visible={showModal}
          onChangeVisible={onToggleModal}
          onConfirmCallback={onSaveLinkCallback}
        />
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleShopMyShelf)
