import Button from 'antd/lib/button'
import { Col, Row } from 'antd/lib/grid'
import DragDropContext from 'components/DragDropContext'
import { Icon } from 'components/Icon'
import PortalComponent from 'components/PortalComponent/PortalComponent'
import { Text } from 'components/Typography'
import { SEGMENT_EVENTS } from 'constants/segment'
import { useAnalytics } from 'hooks/useAnalytics'
import { useModules } from 'hooks/useModules'
import {
  TalentProfileModule,
  YoutubeVideoItem
} from 'models/talent/talent-profile-module.model'
import React, { useCallback, useEffect, 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 { isEmptyModule } from 'utils/modules'
import YoutubeVideoCardModule from '../../../components/YoutubeVideoCardModule'
import YoutubeVideoEditorModal from '../../../components/YoutubeVideoEditorModal/YoutubeVideoEditorModal'
import ModuleEditor from '../ModuleEditor'
import EmptyModule from './EmptyModule'
import { useWindowSize } from '../../../hooks'
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'

interface ModuleYoutubeVideoProps {
  module: TalentProfileModule<YoutubeVideoItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleYoutubeVideo: React.FC<ModuleYoutubeVideoProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const { sendSegmentEvent } = useAnalytics()
  const profileContext = useModules()
  const [youtubeList, setYoutubeList] = useState<YoutubeVideoItem[]>([])
  const [showModal, setShowModal] = useState(false)
  const [youtubeEditState, setYoutubeEditState] = useState<{
    isEdit: boolean
    youtube?: YoutubeVideoItem
    youtubeEditIndex?: number
  }>({
    isEdit: false
  })
  const localizationSelected = useTypedSelector(selectLocalizationSelected)
  const { width } = useWindowSize()
  const isMobileStyleChangesEnabled = width && width <= 768
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED)
  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

  useEffect(() => {
    setYoutubeList(
      module.items.map((youtube, index) => ({
        ...youtube,
        order: index
      }))
    )
    return () => {}
  }, [module.items, module.visible])

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

  const onAddYoutube = useCallback(() => {
    trackStartAddingItemToModule(module)
    setYoutubeEditState(preState => ({
      ...preState,
      isEdit: false,
      youtube: undefined,
      youtubeIndex: undefined
    }))
    setShowModal(true)
  }, [])

  const onEditYoutube = useCallback((youtube: YoutubeVideoItem) => {
    setYoutubeEditState(preState => ({
      ...preState,
      isEdit: true,
      youtube: youtube,
      youtubeIndex: youtube.order
    }))

    setShowModal(true)
  }, [])

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

  const onSaveYoutubeCallback = useCallback(
    (youtube: YoutubeVideoItem) => {
      let moduleEdit
      if (youtubeEditState.isEdit) {
        moduleEdit = {
          ...module,
          items: ArrayServices.updateWithIndex(
            module.items,
            youtube.order as number,
            youtube
          ),
          isUpdate: true
        }
      } else {
        moduleEdit = {
          ...module,
          items: ArrayServices.unshift(module.items, youtube),
          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,
      youtubeEditState,
      localizationSelected,
      profileContext.setModule,
      sendSegmentEvent
    ]
  )

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

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

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <YoutubeVideoEditorModal
          isEdit={youtubeEditState.isEdit}
          item={youtubeEditState.youtube}
          show={showModal}
          toggleModal={onToggleModal}
          onConfirmCallback={onSaveYoutubeCallback}
        />
        {isEmptyModule(module) ? (
          <React.Fragment>
            <EmptyModule titleAction="Add New Video" onClick={onAddYoutube} />
          </React.Fragment>
        ) : (
          <React.Fragment>
            <Row
              align="middle"
              justify="space-between"
              className={isMobileStyleChangesEnabled ? 'm__b--8' : 'm__b--24'}
            >
              <Col className="height--32">
                <Button
                  className="add-item-btn p--0"
                  type="link"
                  onClick={onAddYoutube}
                >
                  <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>
              </Col>
              <Col>
                <Text preset="medium14" className="text--default opacity-6">
                  {youtubeList.length}&nbsp;
                  {youtubeList.length > 1 ? 'videos added' : 'video added'}
                </Text>
              </Col>
            </Row>
            <DragDropContext
              droppableId="youtube-child-drop"
              listClassName="product-list"
              itemIdPrefix="youtube"
              direction="vertical"
              list={youtubeList}
              onDropEndCallback={onDropEndYoutubes}
            >
              {(dragProvided, snapshot, item, youtubeIndex) => {
                const isRender = active ? active : youtubeIndex < 2

                return isRender ? (
                  <PortalComponent
                    innerRef={dragProvided.innerRef}
                    key={youtubeIndex}
                    namespaceClass="product-list"
                    provided={dragProvided}
                    snapshot={snapshot}
                    single={youtubeList?.length === 1}
                  >
                    <YoutubeVideoCardModule
                      titleShortcut
                      disableDragDrop={module.items.length <= 1}
                      index={youtubeIndex}
                      disableDrag={youtubeList?.length === 1}
                      item={item}
                      onEdit={onEditYoutube}
                      onDelete={onDeleteYoutube}
                      dragHandleProps={dragProvided.dragHandleProps}
                      module={module}
                      isInCollection={false}
                    />
                  </PortalComponent>
                ) : (
                  <></>
                )
              }}
            </DragDropContext>
            {!active && youtubeList.length > 2 && (
              <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
                <Text preset="medium14" className="opacity-6">
                  +{youtubeList.length - 2} More
                </Text>
              </div>
            )}
          </React.Fragment>
        )}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleYoutubeVideo)
