import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Button, Col, Row } from 'antd'

import DragDropContext from 'components/DragDropContext'
import PortalComponent from 'components/PortalComponent/PortalComponent'
import { Text } from 'components/Typography'
import { useModules } from 'hooks/useModules'
import MediaGalleryModal from 'components/MediaGalleryModal'
import { DraggableProvidedDragHandleProps } from 'react-beautiful-dnd'
import { Icon } from '../../../components/Icon'
import { Paragraph } from '../../../components/Typography'
import reduce from 'lodash/reduce'
import ModuleEditor from '../ModuleEditor'
import { useWindowSize } from '../../../hooks'
import {
  MediaGalleryItem,
  TalentProfileModule
} from '../../../models/talent/talent-profile-module.model'
import MediaGalleryCardModule from '../../../components/MediaGalleryCardModule'
import {
  FLAGS,
  IfFeatureDisabled,
  IfFeatureEnabled,
  useFeatureIsOn
} from '@komi-app/flags-sdk'
import When from '@komi-app/when'
import { useAnalyticsStartItemCreation } from 'hooks/useAnalyticsStartItemCreation'
import { useAnalyticsCompleteItemCreation } from 'hooks/useAnalyticsCompleteItemCreation'

interface ModuleTikTokProps {
  module: TalentProfileModule<MediaGalleryItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleMediaGallery: React.FC<ModuleTikTokProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const profileContext = useModules()
  const isMediaGalleryVideosEnabled = useFeatureIsOn(
    FLAGS.FEAT_SB_637_ADD_VIDEOS_TO_MEDIA_GALLERY
  )
  const isThumbnailJumpingFixEnabled = useFeatureIsOn(
    FLAGS.FIX_SB_870_THUMBNAILS_JUMPING_ON_UPDATE_MEDIA_GALLERY
  )

  const [modalVisible, setModalVisible] = useState(false)
  const [modalItem, setModalItem] = useState<MediaGalleryItem | undefined>(
    undefined
  )

  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

  const { width } = useWindowSize()
  const isMobileStyleChangesEnabled = width && width <= 768

  const itemList = useMemo(() => {
    if (isMediaGalleryVideosEnabled) {
      return module.items
    }

    return module.items.filter(item => !isIframeVideo(item.src))
  }, [module.items, isMediaGalleryVideosEnabled])

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

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

  const onAddItemClicked = useCallback(() => {
    trackStartAddingItemToModule(module)
    setModalItem(undefined)
    setModalVisible(true)
  }, [])

  const onEditItemClicked = useCallback(
    (mediaGalleryItem: MediaGalleryItem) => {
      setModalItem(mediaGalleryItem)
      setModalVisible(true)
    },
    []
  )

  const onAddMediaGalleryItem = useCallback(
    (mediaGalleryItem: MediaGalleryItem) => {
      const moduleEdit = {
        ...module,
        items: [mediaGalleryItem, ...module.items].map((item, index) => ({
          ...item,
          order: index
        })),
        isUpdate: true
      }
      onEditModuleCallback(moduleEdit)
      trackCompleteAddingItemToModule(moduleEdit)
      setModalVisible(false)
    },
    [module, onEditModuleCallback]
  )

  const onEditMediaGalleryItem = useCallback(
    (existingItem: MediaGalleryItem, newItem: MediaGalleryItem) => {
      const items = module.items.map(item => {
        if (item.order === existingItem.order) {
          return { ...item, ...newItem }
        }
        return item
      })

      onEditModuleCallback({
        ...module,
        items,
        isUpdate: true
      })

      setModalVisible(false)
      setModalItem(undefined)
    },
    [module, onEditModuleCallback]
  )

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

      onEditModuleCallback({
        ...module,
        items,
        isUpdate: true
      })
    },
    [module, profileContext.setModule]
  )

  const renderContent = () => {
    if (!itemList.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={onAddItemClicked}
                >
                  <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 Item
                    </Text>
                  </div>
                </Button>
              </Row>
            </Col>
          </Row>
        </React.Fragment>
      )
    }

    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={onAddItemClicked}
            >
              <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 Item
                </Text>
              </div>
            </Button>
          </Col>
          <Col>
            <Text preset="medium14" className="text--default opacity-6">
              {itemList.length}&nbsp;
              {itemList.length > 1 ? 'item added' : 'items added'}
            </Text>
          </Col>
        </Row>
        <DragDropContext
          droppableId="tiktok-child-drop"
          listClassName="product-list"
          itemIdPrefix="tiktok"
          direction="vertical"
          list={itemList}
          onDropEndCallback={onDropEnd}
        >
          {(dragProvided, snapshot, item, itemIndex) => {
            const isRender = active ? active : itemIndex < 2

            let key
            if (isThumbnailJumpingFixEnabled) {
              key = item.id || item.thumbnailSrc || item.src
            } else {
              key = itemIndex
            }

            return isRender ? (
              <PortalComponent
                innerRef={dragProvided.innerRef}
                key={key}
                namespaceClass="product-list"
                provided={dragProvided}
                snapshot={snapshot}
                single={itemList?.length === 1}
              >
                <MediaGalleryCardModule
                  titleShortcut
                  index={itemIndex}
                  disableDrag={itemList?.length === 1}
                  item={item}
                  dragHandleProps={dragProvided.dragHandleProps || undefined}
                  module={module}
                  onEdit={onEditItemClicked}
                  onDelete={onDeleteMediaGalleryItem}
                />
              </PortalComponent>
            ) : (
              <></>
            )
          }}
        </DragDropContext>
        {!active && itemList.length > 2 && (
          <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
            <Text preset="medium14" className="opacity-6">
              +{itemList.length - 2} More
            </Text>
          </div>
        )}
      </React.Fragment>
    )
  }

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <IfFeatureEnabled feature={FLAGS.FIX_SB_758_DESTROY_MODAL_ON_CLOSE}>
          <When
            value={modalVisible}
            then={
              <MediaGalleryModal
                visible
                existingItem={modalItem}
                onChangeVisible={setModalVisible}
                onItemAdded={onAddMediaGalleryItem}
                onItemEdited={onEditMediaGalleryItem}
              />
            }
          />
        </IfFeatureEnabled>
        <IfFeatureDisabled feature={FLAGS.FIX_SB_758_DESTROY_MODAL_ON_CLOSE}>
          <MediaGalleryModal
            visible={modalVisible}
            existingItem={modalItem}
            onChangeVisible={setModalVisible}
            onItemAdded={onAddMediaGalleryItem}
            onItemEdited={onEditMediaGalleryItem}
          />
        </IfFeatureDisabled>
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  )
}

export function isIframeVideo(src: string): boolean {
  return src.endsWith('/iframe')
}

export default React.memo(ModuleMediaGallery)
