import classNames from 'classnames'
import CaptureFieldItem from 'components/CaptureFieldItem'
import * as React from 'react'
import { DataCaptureFieldItem } from 'models/talent/talent-profile-module.model'
import DragDropContext from '../DragDropContext'
import PortalComponent from '../PortalComponent/PortalComponent'
const CaptureFieldItemMemo = React.memo(CaptureFieldItem)
import { ArrayServices } from 'utils/array'
import { useCallback } from 'react'

interface CaptureFieldListProps {
  items: DataCaptureFieldItem[]
  onSetItems?: (links: DataCaptureFieldItem[]) => void
  className?: string
  hideTags?: boolean
  activeFieldIndex?: number
  setActiveFieldIndex?: (value: number) => void
}

const CaptureFieldList = ({
  items,
  onSetItems,
  className,
  activeFieldIndex,
  setActiveFieldIndex
}: CaptureFieldListProps) => {
  const onDropEndModules = (list: DataCaptureFieldItem[]) => {
    onSetItems?.(list)
  }
  const onSetItem = (index: number) => (value: any) => {
    const list = [...items]
    list[index] = { ...list[index], ...value }
    onSetItems?.(list)
  }

  const onRemoveItem = (index: number) => () => {
    const newList = ArrayServices.removeWithIndex(items, index)
    onSetItems?.(newList)
  }
  const onClickActive = useCallback(
    (index: number) => () => {
      setActiveFieldIndex?.(index)
    },
    [setActiveFieldIndex]
  )

  return (
    <div>
      <React.Fragment>
        <DragDropContext
          droppableId="modules-drop"
          listClassName={classNames(
            'modules-list capture-field-list',
            className
          )}
          itemIdPrefix="module"
          list={items}
          onDropEndCallback={onDropEndModules}
        >
          {(dragProvided, snapshot, item, index) => (
            <PortalComponent
              innerRef={dragProvided.innerRef}
              namespaceClass="module-list"
              provided={dragProvided}
              snapshot={snapshot}
            >
              <CaptureFieldItemMemo
                name={item.name}
                key={item.name}
                dragHandleProps={dragProvided.dragHandleProps}
                edit={item.edit}
                isDisableDragged={item.edit}
                onSetItem={onSetItem(index)}
                onRemoveItem={onRemoveItem?.(index)}
                defaultValue={item.label}
                required={item.required}
                type={item.type}
                field={item}
                isActive={activeFieldIndex === index}
                onClick={onClickActive(index)}
              />
            </PortalComponent>
          )}
        </DragDropContext>
      </React.Fragment>
    </div>
  )
}

export default React.memo(CaptureFieldList)
