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 {
  InstagramReelItem,
  TalentProfileModule
} from 'models/talent/talent-profile-module.model'
import React, { useCallback, useMemo, useState } from 'react'
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 InstagramReelsModal from 'components/InstagramReelsModal'
import InstagramReelsCardModule from 'components/InstagramReelsCardModule'
import { useAnalyticsStartItemCreation } from 'hooks/useAnalyticsStartItemCreation'
import { useAnalyticsCompleteItemCreation } from 'hooks/useAnalyticsCompleteItemCreation'

interface ModuleReelProps {
  module: TalentProfileModule<InstagramReelItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleReel: React.FC<ModuleReelProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const profileContext = useModules()
  const [modalVisible, setModalVisible] = useState(false)
  const [modalItem, setModalItem] = useState<InstagramReelItem | undefined>(
    undefined
  )

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

  const reelList = useMemo(() => module.items, [module.items])
  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

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

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

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

  const onEditVideoClicked = useCallback(
    (reel: InstagramReelItem) => {
      setModalItem(reel)
      setModalVisible(true)
    },
    [setModalVisible]
  )

  const onAddReel = useCallback(
    (url: string) => {
      const moduleEdit = {
        ...module,
        items: [{ url, order: module.items.length }, ...module.items],
        isUpdate: true
      }
      onEditModuleCallback(moduleEdit)
      trackCompleteAddingItemToModule(moduleEdit)
      setModalVisible(false)
    },
    [module, onEditModuleCallback]
  )

  const onEditReel = useCallback(
    (existingItem: InstagramReelItem, url: string) => {
      const items = module.items.map(item => {
        if (item.order === existingItem.order) {
          return { ...item, url }
        }
        return item
      })

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

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

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

      onEditModuleCallback({
        ...module,
        items,
        isUpdate: true
      })
    },
    [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={onAddVideoClicked}
                >
                  <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>
      )
    }

    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={onAddVideoClicked}
            >
              <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">
              {reelList.length}&nbsp;
              {reelList.length > 1 ? 'videos added' : 'video added'}
            </Text>
          </Col>
        </Row>
        <DragDropContext
          droppableId="reel-child-drop"
          listClassName="product-list"
          itemIdPrefix="reel"
          direction="vertical"
          list={reelList}
          onDropEndCallback={onDropEndReels}
        >
          {(dragProvided, snapshot, item, reelIndex) => {
            const isRender = active ? active : reelIndex < 2

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

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <InstagramReelsModal
          visible={modalVisible}
          existingItem={modalItem}
          onChangeVisible={setModalVisible}
          onVideoAdded={onAddReel}
          onVideoEdited={onEditReel}
        />
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleReel)
