import { Row } from 'antd'
import DragDropContext from 'components/DragDropContext'
import { useModules } from 'hooks/useModules'
import {
  GroupItem,
  TalentProfileModule
} from 'models/talent/talent-profile-module.model'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { DraggableProvidedDragHandleProps } from 'react-beautiful-dnd'
import AddModule from '../AddModule/AddModule'
import ModuleEditor from '../ModuleEditor'
import ModulePortal from '../ModulePortal/ModulePortal'
import { useAnalyticsCompleteItemCreation } from 'hooks/useAnalyticsCompleteItemCreation'

interface ModuleGroupProps {
  module: TalentProfileModule<GroupItem>
  dragHandleProps?: DraggableProvidedDragHandleProps
  active: boolean
}

const ModuleGroup: React.FC<ModuleGroupProps> = ({
  module,
  dragHandleProps
}) => {
  const profileContext = useModules()
  const [moduleList, setModuleList] = useState<any>([])
  const { trackCompleteAddingItemToModule } = useAnalyticsCompleteItemCreation()

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

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

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

  return (
    <React.Fragment>
      <ModuleEditor module={module} dragHandleProps={dragHandleProps}>
        <React.Fragment>
          <Row className="m__b--20 group-module-add">
            <AddModule groupId={module.id} isSolid={false} />
          </Row>
          <DragDropContext
            droppableId="group-module-child-drop"
            listClassName="product-list"
            itemIdPrefix="group-module"
            direction="vertical"
            list={moduleList}
            onDropEndCallback={onDropEndItem}
          >
            {(dragProvided, snapshot, item, index) => {
              return (
                <ModulePortal
                  key={index}
                  provided={dragProvided}
                  snapshot={snapshot}
                  module={item as any}
                />
              )
            }}
          </DragDropContext>
        </React.Fragment>
      </ModuleEditor>
    </React.Fragment>
  )
}

export default React.memo(ModuleGroup)
