import Button from 'antd/lib/button'
import DragDropContext from 'components/DragDropContext'
import EventCardModule from 'components/EventCardModule'
import EventEditorModal from 'components/EventEditorModal/EventEditorModal'
import { Icon } from 'components/Icon'
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 {
  BaseItem,
  EventItem,
  TalentProfileModule
} from 'models/talent/talent-profile-module.model'
import React, { useCallback, useEffect, 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 {
  flipVisibilityForItemAndCloneArray,
  isEmptyModule
} from 'utils/modules'
import ModuleEditor from '../ModuleEditor'
import EmptyModule from './EmptyModule'
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'
import { useAnalyticsStartItemCreation } from 'hooks/useAnalyticsStartItemCreation'

const EventCardMemo = React.memo(EventCardModule)

interface ModuleEventsProps {
  module: TalentProfileModule<EventItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleEvents: React.FC<ModuleEventsProps> = ({
  module,
  dragHandleProps,
  active
}) => {
  const { sendSegmentEvent } = useAnalytics()
  const useAnalyticsSDK = useFeatureIsOn(FLAGS.USE_ANALYTICS_SDK_TALENT)
  const { createTracker } = useCreatorTracking()
  const elementCreate = createTracker(CreatorEvent.ELEMENT_CREATED)

  const profileContext = useModules()
  const [events, setEvents] = useState<EventItem[]>([])
  const [showModal, setShowModal] = useState(false)
  const [itemEditState, setItemEditState] = useState<{
    isEdit: boolean
    item?: EventItem
    itemEditIndex?: number
  }>({
    isEdit: false
  })
  const localizationSelected = useTypedSelector(selectLocalizationSelected)
  const { trackStartAddingItemToModule } = useAnalyticsStartItemCreation()
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

  useEffect(() => {
    setEvents(
      module.items.map((item, index) => ({
        ...item,
        order: index
      }))
    )
    return () => {}
  }, [module.items, module.visible])

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

  const onAddItem = useCallback(() => {
    trackStartAddingItemToModule(module)
    setItemEditState(preState => ({
      ...preState,
      isEdit: false,
      item: undefined,
      itemIndex: undefined
    }))
    setShowModal(true)
  }, [])

  const onEditItem = useCallback((item: EventItem) => {
    setItemEditState(preState => ({
      ...preState,
      isEdit: true,
      item,
      itemIndex: item.order
    }))
    setShowModal(true)
  }, [])

  const onDeleteItem = useCallback(
    (item: EventItem) => {
      profileContext.setModule({
        ...module,
        items: ArrayServices.removeWithIndex(
          module.items,
          item.order as number
        ),
        isUpdate: true
      })
    },
    [module, profileContext.setModule]
  )

  const onSaveItemCallback = useCallback(
    (item: EventItem) => {
      let moduleEdit
      if (itemEditState.isEdit) {
        moduleEdit = {
          ...module,
          items: ArrayServices.updateWithIndex(
            module.items,
            item.order as number,
            item
          ),
          isUpdate: true
        }
      } else {
        moduleEdit = {
          ...module,
          items: ArrayServices.unshift(module.items, item),
          isUpdate: true
        }
      }
      profileContext.setModule(moduleEdit)
      trackCompleteAddingItemToModule(moduleEdit)
      const { pageId, pageName, type } = trackingProps(
        moduleEdit.type || 'CUSTOM EVENT',
        localizationSelected
      )

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

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

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

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <EventEditorModal
          isEdit={itemEditState.isEdit}
          item={itemEditState.item}
          show={showModal}
          toggleModal={onToggleModal}
          onConfirmCallback={onSaveItemCallback}
        />
        {isEmptyModule(module) ? (
          <React.Fragment>
            <EmptyModule titleAction="Add New Event" onClick={onAddItem} />
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div className="d--flex justify__content--between align__items--center m__b--22">
              <Button
                className="add-item-btn p--0"
                type="link"
                onClick={onAddItem}
              >
                <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 Event
                  </Text>
                </div>
              </Button>
              <Text preset="medium14" className="text--default opacity-6">
                {`${events.length} date${events.length > 1 ? 's' : ''} added`}
              </Text>
            </div>

            <DragDropContext
              droppableId="event-child-drop"
              listClassName="product-list"
              itemIdPrefix="event"
              direction="vertical"
              list={events}
              onDropEndCallback={onDropEndItems}
            >
              {(dragProvided, snapshot, item, itemIndex) => {
                return active ? (
                  <PortalComponent
                    innerRef={dragProvided.innerRef}
                    key={itemIndex}
                    namespaceClass="product-list"
                    provided={dragProvided}
                    snapshot={snapshot}
                    single={events?.length === 1}
                  >
                    <EventCardMemo
                      titleShortcut
                      index={itemIndex}
                      disableDrag={events?.length === 1}
                      item={item}
                      onEdit={onEditItem}
                      onDelete={onDeleteItem}
                      dragHandleProps={dragProvided.dragHandleProps}
                      module={module}
                    />
                  </PortalComponent>
                ) : itemIndex < 2 ? (
                  <PortalComponent
                    innerRef={dragProvided.innerRef}
                    key={itemIndex}
                    namespaceClass="product-list"
                    provided={dragProvided}
                    snapshot={snapshot}
                    single={events?.length === 1}
                  >
                    <EventCardMemo
                      titleShortcut
                      index={itemIndex}
                      disableDrag={events?.length === 1}
                      item={item}
                      onEdit={onEditItem}
                      onDelete={onDeleteItem}
                      dragHandleProps={dragProvided.dragHandleProps}
                      module={module}
                    />
                  </PortalComponent>
                ) : (
                  <></>
                )
              }}
            </DragDropContext>
            {!active && events.length > 2 && (
              <div className="d--flex justify__content--end align__items--center m__t--20 cursor-pointer">
                <Text preset="medium14" className="opacity-6">
                  +{events.length - 2} More
                </Text>
              </div>
            )}
          </React.Fragment>
        )}
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleEvents)
