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 {
  TalentProfileModule,
  TikTokAutomationItem,
  TikTokItem
} from 'models/talent/talent-profile-module.model'
import React, { useCallback, useEffect, useMemo } from 'react'
import { Icon } from '../../../components/Icon'
import { Paragraph } from '../../../components/Typography'
import ModuleEditor from '../ModuleEditor'
import TikTokVideoCardModule from 'components/TikTokVideoCardModule'
import { useHistory } from 'react-router-dom'
import { ModuleTikTokAutomationProps } from './ModuleTikTokAutomation'
import { useWindowSize } from 'hooks'
import { routes, ShortVideoPage } from '../AddShortVideo/routes'
import { useAnalyticsStartItemCreation } from 'hooks/useAnalyticsStartItemCreation'
import { useAnalyticsCompleteItemCreation } from 'hooks/useAnalyticsCompleteItemCreation'

const ModuleTikTokSemiAutomated: React.FC<ModuleTikTokAutomationProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const automationItem = module.items.length > 0 ? module.items[0] : undefined
  const profileContext = useModules()
  const navigate = useHistory()

  const { width } = useWindowSize()
  const isMobileStyleChangesEnabled = width && width <= 768
  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

  const tiktokList = useMemo(
    () => automationItem?.links || [],
    [automationItem?.links]
  )

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

  const onDropEndTikTokVideos = useCallback(
    (list: TikTokItem[]) => {
      const newItem: TikTokAutomationItem = {
        ...module.items[0],
        links: list.map((item, index) => ({ ...item, order: index }))
      }

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

  const onAddVideoClicked = useCallback(() => {
    trackStartAddingItemToModule(module)
    navigate.push(
      `/admin/modules/tiktok${routes[ShortVideoPage.AUTOMATION_EDIT]}?id=${module.id}&accountId=${automationItem?.tiktokAccountId}`
    )
  }, [module.id, navigate, automationItem?.tiktokAccountId])

  const onDeleteTikTokVideo = useCallback(
    (tiktok: TikTokItem) => {
      if (!automationItem) return

      const newLinks = automationItem.links
        .filter(item => item.order !== tiktok.order)
        .map((item, index) => ({ ...item, order: index }))

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

  const onVisibilityChange = useCallback(
    (item: TikTokItem) => {
      if (!automationItem) return

      const newLinks = automationItem.links.map(link => {
        if (link.order === item.order) {
          return { ...link, visible: !link.visible }
        }
        return link
      })

      const allVideosHidden = newLinks.every(link => !link.visible)

      onEditModuleCallback({
        ...module,
        items: [
          {
            ...automationItem,
            links: newLinks
          }
        ],
        isUpdate: true,
        visible: !allVideosHidden
      })
    },
    [module, profileContext.setModule, automationItem]
  )

  useEffect(() => {
    if (!automationItem || !module.visible) return

    const allVideosHidden = automationItem.links.every(link => !link.visible)

    // If all videos are hidden and the module is visible, show all videos
    if (allVideosHidden) {
      onEditModuleCallback({
        ...module,
        isUpdate: true,
        items: [
          {
            ...automationItem,
            links: automationItem.links.map(link => ({
              ...link,
              visible: true
            }))
          }
        ]
      })
    }
  }, [module.visible, automationItem, onVisibilityChange])

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

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

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleTikTokSemiAutomated)
