import React, { Dispatch, SetStateAction } from 'react'
import { FormInstance } from 'antd'

import PortalComponent from 'components/PortalComponent/PortalComponent'
import DragDropContext from 'components/DragDropContext'

import { SmartLinkSelectionItemMemo } from './SmartLinkSelectionItem'

import { DspLink } from 'types/dsp'

import { ArrayServices } from 'utils/array'

interface SmartLinkSelectionItemsProps {
  form?: FormInstance
  dspLinks: DspLink[]
  setDspLinks: Dispatch<SetStateAction<DspLink[]>>
}

export const SmartLinkSelectionItems: React.FC<
  SmartLinkSelectionItemsProps
> = ({ form, dspLinks, setDspLinks }) => {
  const onDropEndLinks = async (links: DspLink[]) => {
    setDspLinks(links)
  }

  const onRemoveItem = (index: number) => () => {
    const newList = ArrayServices.removeWithIndex(dspLinks, index)
    setDspLinks(newList)
  }

  const setItem = (index: number) => (link: DspLink) => {
    const updatedDspLinks = ArrayServices.updateWithIndex(dspLinks, index, link)
    setDspLinks(updatedDspLinks)
  }

  return (
    <React.Fragment>
      <DragDropContext
        droppableId="modules-drop"
        listClassName="modules-list m__t--14"
        itemIdPrefix="module"
        list={dspLinks}
        onDropEndCallback={onDropEndLinks}
      >
        {(dragProvided, snapshot, item, index) => {
          return (
            <PortalComponent
              innerRef={dragProvided.innerRef}
              namespaceClass="module-list"
              provided={dragProvided}
              snapshot={snapshot}
            >
              <SmartLinkSelectionItemMemo
                dragHandleProps={dragProvided.dragHandleProps}
                dragDisabled={dspLinks.length === 1}
                form={form}
                item={item}
                index={index}
                removeItem={onRemoveItem(index)}
                setItem={setItem(index)}
              />
            </PortalComponent>
          )
        }}
      </DragDropContext>
    </React.Fragment>
  )
}
