import { Button, Col, Row } from 'antd'
import DragDropContext from 'components/DragDropContext'
import PortalComponent from 'components/PortalComponent/PortalComponent'
import { Text } from 'components/Typography'
import YoutubeVideoCardModule from 'components/YoutubeVideoCardModule'
import YoutubeModal from 'components/YoututeModal'
import { YOUTUBE_MODAL_STEP } from 'constants/module'
import { SEGMENT_EVENTS } from 'constants/segment'
import { useAnalytics } from 'hooks/useAnalytics'
import { useModules } from 'hooks/useModules'
import {
  TalentProfileModule,
  YoutubeItem,
  YoutubeVideoItem
} 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 reduce from 'lodash/reduce'
import ModuleEditor from '../ModuleEditor'
import YoutubeCollectionItem from 'components/YoutubeCollectionItem'
import { useWindowSize } from '../../../hooks'
import { ModuleType } from '@komi-app/shared-types'
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 ModuleYoutubeProps {
  module: TalentProfileModule<YoutubeItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleYoutube: React.FC<ModuleYoutubeProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const { sendSegmentEvent } = useAnalytics()
  const profileContext = useModules()
  const localizationSelected = useTypedSelector(selectLocalizationSelected)
  const [modalStatus, setModalStatus] = useState<{
    visible: boolean
    status: YOUTUBE_MODAL_STEP
    item?: YoutubeItem
  }>({
    visible: false,
    status: YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE,
    item: undefined
  })
  const item = useMemo(() => {
    return module.items[0]
  }, [module.items])

  const { width } = useWindowSize()
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED)
  const isMobileStyleChangesEnabled = width && width <= 768

  const youtubeList = useMemo(() => module.items, [module.items])

  const { loadingShop, thirdPartyData } = profileContext
  // console.log("Youtube Module : ",  JSON.stringify(module))
  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 collection = useMemo(() => data?.collection, [data])
  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

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

  const onEditYoutubeVideo = useCallback((youtube: YoutubeItem) => {
    setModalStatus({
      visible: true,
      item: undefined,
      status: YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE
    })
    setTimeout(() => {
      setModalStatus({
        visible: true,
        item: youtube,
        status: YOUTUBE_MODAL_STEP.INDIVIDUAL_VIDEO
      })
    }, 50)
  }, [])

  const onAddYoutubeVideo = useCallback(() => {
    trackStartAddingItemToModule(module)
    setModalStatus({
      visible: true,
      item: undefined,
      status: YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE
    })
    setTimeout(() => {
      setModalStatus(values => ({
        ...values,
        status: YOUTUBE_MODAL_STEP.INDIVIDUAL_VIDEO
      }))
    }, 50)
  }, [])

  const onEditYoutubeCollection = useCallback(() => {
    setModalStatus({
      visible: true,
      item: undefined,
      status: YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE
    })
    setTimeout(() => {
      setModalStatus(values => ({
        ...values,
        item,
        status: YOUTUBE_MODAL_STEP.VIDEO_COLLECTION
      }))
    }, 50)
  }, [item])

  const onSaveYoutubeVideoCallback = useCallback(
    (data: any) => {
      let moduleEdit
      if (modalStatus.item) {
        moduleEdit = {
          ...module,
          items: ArrayServices.updateWithIndex(
            module.items,
            modalStatus.item.order as number,
            { ...modalStatus.item, ...data }
          ),
          isUpdate: true
        }
      } else {
        moduleEdit = {
          ...module,
          items: [{ ...data, order: 0 }, ...module.items].map(
            (el, index: number) => ({ ...el, order: index })
          ),
          isUpdate: true,
          type:
            modalStatus.status === YOUTUBE_MODAL_STEP.VIDEO_COLLECTION
              ? ModuleType.YOUTUBE_COLLECTION
              : ModuleType.YOUTUBE_VIDEO
        }

        const { pageId, pageName, type } = trackingProps(
          moduleEdit.type,
          localizationSelected
        )

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

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

  const onAddYoutubeModule = useCallback(() => {
    trackStartAddingItemToModule(module)
    setModalStatus({
      visible: true,
      status: YOUTUBE_MODAL_STEP.SELECT_YOUTUBE_TYPE,
      item: undefined
    })
  }, [])

  const onDeleteYoutubeVideo = useCallback(
    (youtube: YoutubeItem) => {
      const items = reduce(
        module.items,
        (results: any, item: any) => {
          if (item.order !== youtube.order) {
            return [...results, { ...item, order: results.length }]
          }
          return results
        },
        []
      )

      profileContext.setModule({
        ...module,
        items,
        isUpdate: true,
        type: !items.length ? ModuleType.YOUTUBE : module.type
      })
    },
    [module, profileContext.setModule]
  )

  const renderContent = () => {
    if (!module.items.length) {
      return (
        <React.Fragment>
          <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">
                Nothing Here Yet
              </Paragraph>
              <Paragraph preset="regular14" className="d--block text--grey4">
                Click the button below to get started
              </Paragraph>
            </Col>
            <Col span={24} className="height--32 m__t--20">
              <Row justify="center">
                <Button
                  className="add-item-btn p--0"
                  type="link"
                  onClick={onAddYoutubeModule}
                >
                  <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>
              </Row>
            </Col>
          </Row>
        </React.Fragment>
      )
    }
    if (module.type === ModuleType.YOUTUBE_COLLECTION) {
      return (
        <YoutubeCollectionItem
          loading={loading}
          collection={collection}
          item={item}
          onDelete={onDeleteYoutubeVideo}
          active={active}
          module={module}
        />
      )
    }
    return (
      <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={onAddYoutubeVideo}
            >
              <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={onDropEndYoutubeVideos}
        >
          {(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={onEditYoutubeVideo}
                  onDelete={onDeleteYoutubeVideo}
                  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>
    )
  }

  return (
    <React.Fragment>
      <ModuleEditor
        module={module}
        dragHandleProps={dragHandleProps}
        onEditYoutube={onEditYoutubeCollection}
      >
        <YoutubeModal
          show={modalStatus.visible}
          setStatusModal={setModalStatus}
          step={modalStatus.status}
          onSubmit={onSaveYoutubeVideoCallback}
          item={modalStatus.item}
          cancellable={module.type !== ModuleType.YOUTUBE}
        />
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleYoutube)
