import './ModuleOndemandVideo.scss'
import OnDemandEditorModal from 'components/OnDemandEditorModal/OnDemandEditorModal'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { DraggableProvidedDragHandleProps } from 'react-beautiful-dnd'
import {
  OnDemandVideoItem,
  TalentProfileModule
} from 'models/talent/talent-profile-module.model'
import { ArrayServices } from 'utils/array'
import ModuleEditor from '../ModuleEditor'
import ProfileContext from '../ProfileContext'
import EmptyModule from './EmptyModule'
import { Text } from 'components/Typography'
import Button from 'antd/lib/button'
import { Icon } from 'components/Icon'
import DragDropContext from 'components/DragDropContext'
import PortalComponent from 'components/PortalComponent/PortalComponent'
import OnDemandCard from 'components/OnDemandCard'
import { useAnalytics } from 'hooks/useAnalytics'
import { SEGMENT_EVENTS } from 'constants/segment'
import { selectLocalizationSelected } from 'redux/User/selector'
import { useTypedSelector } from 'redux/rootReducer'
import { useModules } from 'hooks/useModules'
import { isEmptyModule } from 'utils/modules'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'
import { trackingProps } from 'utils/tracking'
import { useAnalyticsStartItemCreation } from 'hooks/useAnalyticsStartItemCreation'
import { useAnalyticsCompleteItemCreation } from 'hooks/useAnalyticsCompleteItemCreation'

const OnDemandCardMemo = React.memo(OnDemandCard)

interface ModuleOndemandVideoProps {
  module: TalentProfileModule<OnDemandVideoItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleOndemandVideo: React.FC<ModuleOndemandVideoProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const { sendSegmentEvent } = useAnalytics()
  const profileContext = useModules()
  const [items, setItems] = useState<OnDemandVideoItem[]>([])
  const [showModal, setShowModal] = useState(false)
  const [itemEditState, setItemEditState] = useState<{
    isEdit: boolean
    item?: OnDemandVideoItem
  }>({
    isEdit: false
  })
  const localizationSelected = useTypedSelector(selectLocalizationSelected)
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED)
  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

  const totalPriceOfItems = useMemo(() => {
    return module.items.reduce(
      (acc, curr) => (acc += curr.experiencePrice || 0),
      0
    )
  }, [module])

  useEffect(() => {
    setItems(
      (module.items as OnDemandVideoItem[]).map((exp, index) => ({
        ...exp,
        order: index
      }))
    )
    return () => {}
  }, [module.items])

  const onEditModuleCallback = useCallback(
    (moduleEdit: TalentProfileModule<OnDemandVideoItem>) => {
      profileContext.setModule(moduleEdit)
    },
    [profileContext.setModule]
  )

  const onAddItem = useCallback(() => {
    trackStartAddingItemToModule(module)
    setItemEditState(preState => ({
      ...preState,
      isEdit: false,
      item: undefined,
      itemEditIndex: undefined
    }))
    setShowModal(true)
  }, [])

  const onEditItem = useCallback((item: OnDemandVideoItem) => {
    setItemEditState(preState => ({
      ...preState,
      isEdit: true,
      item: item
    }))
    setShowModal(true)
  }, [])

  const onDeleteItem = useCallback(
    (item: OnDemandVideoItem) => {
      profileContext.setModule({
        ...module,
        items: ArrayServices.removeWithIndex(
          module.items,
          item.order as number
        ),
        isUpdate: true
      })
    },
    [module, profileContext.setModule]
  )

  const onSaveItemCallback = useCallback(
    (item: OnDemandVideoItem) => {
      let moduleEdit
      if (itemEditState.isEdit) {
        moduleEdit = {
          ...module,
          items: ArrayServices.updateWithIndex(
            module.items,
            item.order as number,
            { ...item, experienceId: item.id }
          ),
          isUpdate: true
        }
      } else {
        moduleEdit = {
          ...module,
          items: ArrayServices.unshift(module.items, {
            ...item,
            experienceId: item.id
          }),
          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,
      itemEditState,
      localizationSelected,
      profileContext.setModule,
      sendSegmentEvent
    ]
  )

  const onDropEndProducts = useCallback(
    (list: OnDemandVideoItem[]) => {
      onEditModuleCallback({
        ...module,
        items: list.map((item, index) => ({
          ...item,
          experienceId: item.id,
          order: index
        })),
        isUpdate: true
      })
    },
    [module, onEditModuleCallback]
  )

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

  return (
    <React.Fragment>
      <OnDemandEditorModal
        isEdit={itemEditState.isEdit}
        item={itemEditState.item}
        show={showModal}
        toggleModal={onToggleModal}
        onConfirmCallback={onSaveItemCallback}
      />
      <ModuleEditor
        module={module}
        showStripeWarning={totalPriceOfItems > 0}
        dragHandleProps={dragHandleProps}
      >
        {isEmptyModule(module) ? (
          <React.Fragment>
            <EmptyModule titleAction="Add New Video" onClick={onAddItem} />
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div className="d--flex justify__content--between align__items--center m__b--22">
              <Button
                className="add-item-btn p--0"
                type="link"
                onClick={onAddItem}
              >
                <div className="d--flex justify__content--center align__items--center">
                  <Icon name="add-blue" />
                  <Text preset="semibold18" className="text--blue m__l--4">
                    Add New video
                  </Text>
                </div>
              </Button>
              <Text preset="medium14" className="text--default opacity-6">
                {items.length}&nbsp;
                {items.length > 1 ? 'videos added' : 'video added'}
              </Text>
            </div>

            <DragDropContext
              droppableId="on-demand-child-drop"
              listClassName="on-demand-list"
              itemIdPrefix="on-demand"
              direction="vertical"
              list={items}
              onDropEndCallback={onDropEndProducts}
            >
              {(dragProvided, snapshot, item, itemIndex) => {
                const isRender = active ? active : itemIndex < 2
                return isRender ? (
                  <PortalComponent
                    innerRef={dragProvided.innerRef}
                    key={itemIndex}
                    namespaceClass="on-demand-list"
                    provided={dragProvided}
                    snapshot={snapshot}
                  >
                    <OnDemandCardMemo
                      disableDragDrop={module.items.length <= 1}
                      index={itemIndex}
                      item={item}
                      showPrice
                      titleShortcut
                      onEdit={onEditItem}
                      onDelete={onDeleteItem}
                      dragHandleProps={dragProvided.dragHandleProps}
                    />
                  </PortalComponent>
                ) : (
                  <></>
                )
              }}
            </DragDropContext>
            {!active && items.length > 2 && (
              <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
                <Text preset="medium14" className="opacity-6">
                  +{items.length - 2} More
                </Text>
              </div>
            )}
          </React.Fragment>
        )}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleOndemandVideo)
