import { Col } from 'antd'
import DragDropContext from 'components/DragDropContext'
import LoadingModule from 'components/LoadingModule'
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 {
  SeatedItem,
  TalentProfileModule
} 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 SeatedEditorModal from '../../../components/SeatedEditorModal'
import SteatedEventCard from '../../../components/SeatedEventCard'
import { Icon } from '../../../components/Icon'
import { Paragraph } from '../../../components/Typography'
import ModuleEditor from '../ModuleEditor'
import './ModuleSeated.scss'
import { Alert } from 'antd'
import { FLAGS, useFeatureIsOn } from '@komi-app/flags-sdk'
import { useCreatorTracking, CreatorEvent } from '@komi-app/analytics-sdk'
import { trackingProps } from 'utils/tracking'
import { useAnalyticsCompleteItemCreation } from 'hooks/useAnalyticsCompleteItemCreation'

const SeatedEventCardMemo = React.memo(SteatedEventCard)

interface ModuleSeatedProps {
  module: TalentProfileModule<SeatedItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleSeated: React.FC<ModuleSeatedProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const { sendSegmentEvent } = useAnalytics()
  const profileContext = useModules()
  const localizationSelected = useTypedSelector(selectLocalizationSelected)
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED)
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

  const item = useMemo(() => {
    return module.items[0]
  }, [module.items])
  const [showModal, setShowModal] = useState(false)

  const { loadingShop, thirdPartyData } = profileContext
  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 events = useMemo(
    () => data?.events || { message: null, shows: [] },
    [data]
  )

  const onEditModuleCallback = useCallback(
    (moduleEdit: TalentProfileModule<SeatedItem>) => {
      profileContext.setModule(moduleEdit)
    },
    [profileContext.setModule]
  )
  const onEditSeatedLink = useCallback(() => {
    setShowModal(true)
  }, [])

  const onSaveLinkCallback = useCallback(
    (link: SeatedItem) => {
      const moduleEdit = {
        ...module,
        items: ArrayServices.updateWithIndex(module.items, 0, link),
        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, localizationSelected, profileContext.setModule, sendSegmentEvent]
  )

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

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

  const renderContent = () => {
    if (data && data.status === 'cannot-connect') {
      return (
        <Alert
          message={undefined}
          className={'  p__x--16 bg--serenade border--none'}
          description={
            <div>
              Connection with Seated could not be established at this time. Try
              reloading the page or check back later.
              <br />
              If there is an issue with Seated, this module will be hidden from
              your profile until the connection is reestablished. The rest of
              your profile will not be affected and you can continue making and
              publishing changes as normal.
            </div>
          }
          icon={<Icon name="warning" />}
          showIcon
          closeText={<Icon width={24} height={24} name="close-outline" />}
        />
      )
    }
    if (loading) {
      return <LoadingModule />
    }
    if (!events?.shows?.length) {
      return (
        <React.Fragment>
          {events.status !== 200 &&
            events.message &&
            events.message.length > 0 && (
              <Alert
                message={undefined}
                className={
                  'm__b--16  p__y--8 p__x--16 bg--serenade border--none'
                }
                description={events.message}
                icon={<Icon name="warning" />}
                showIcon
                closable={false}
              />
            )}

          <Col span={24} className="text__align--center">
            <Icon name="empty-module" />
          </Col>
          <Col span={24} className="text__align--center">
            <Paragraph preset="semibold18" className="d--block m__b--4">
              No Events Found
            </Paragraph>
            <Paragraph
              preset="regular16"
              className="d--block subtitle-empty-seated"
            >
              It appears that you have no events on Seated right now. Try adding
              events to your Seated profile or edit your Artist ID.
            </Paragraph>
          </Col>
        </React.Fragment>
      )
    }
    return (
      <React.Fragment>
        <div className="d--flex justify__content--end align__items--center m__b--22">
          <Text preset="medium14" className="opacity-6">
            {events.shows.length}&nbsp;
            {events.shows.length > 1 ? 'dates added' : 'date added'}
          </Text>
        </div>
        <DragDropContext
          droppableId="link-child-drop"
          listClassName="product-list"
          itemIdPrefix="link"
          direction="vertical"
          list={events?.shows}
          onDropEndCallback={onDropEndLinks}
        >
          {(dragProvided, snapshot, item, linkIndex) => {
            const isRender = active ? active : linkIndex < 2
            return isRender ? (
              <PortalComponent
                key={linkIndex}
                innerRef={dragProvided.innerRef}
                namespaceClass="product-list"
                provided={dragProvided}
                snapshot={snapshot}
                single={events?.shows?.length === 1}
              >
                <SeatedEventCardMemo
                  index={linkIndex}
                  titleShortcut
                  item={item as any}
                  dragHandleProps={dragProvided.dragHandleProps}
                />
              </PortalComponent>
            ) : (
              <></>
            )
          }}
        </DragDropContext>
        {!active && events.shows && events.shows.length > 2 && (
          <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
            <Text preset="medium14" className="opacity-6">
              +{events.shows.length - 2} More
            </Text>
          </div>
        )}
      </React.Fragment>
    )
  }
  return (
    <React.Fragment>
      <ModuleEditor
        module={module}
        dragHandleProps={dragHandleProps}
        onEditSeatedLink={onEditSeatedLink}
      >
        <SeatedEditorModal
          isEdit={true}
          item={item}
          visible={showModal}
          onChangeVisible={onToggleModal}
          onConfirmCallback={onSaveLinkCallback}
        />
        {renderContent()}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleSeated)
