import React from 'react';
import useHandleMove from '../Common/useHandleMove';
import {DragAndDropItem, DragAndDropProvider} from "../index";

type MultiValueProps<T> = {
  value?: T[]|null;
  onChange: (value: T[]) => void;
  children: (data: T|any|null, onChange: (data: T) => void, index: number) => React.ReactNode;
  add?: Boolean;
  move?: Boolean;
  index?: Boolean;
};

export default function MultiValue<T>({ value, move, onChange, children, add, index }: MultiValueProps<T>) {
  const arr = value || [];

  const handleMove = useHandleMove(value, onChange);

  if (move) {
      return <DragAndDropProvider onMove={move && handleMove}>
          {arr.map((a, i) => <DragAndDropItem key={i} item={i}>
            {children(a, (val) => onChange(index ? (val === null ? arr.filter((b, a) => i !== a) : arr.map((b, a) => i === a ? val : b)) : (val === null ? arr.filter(b => b !== a) : arr.map(b => b === a ? val : b))), i)}
          </DragAndDropItem>)
      .concat(add === false ? [] : [ <DragAndDropItem key={(value && value.length) || 0} item={null}>
          {children(null, (val) => onChange(arr.concat([val])), (value && value.length) || 0)}
      </DragAndDropItem> ])}
      </DragAndDropProvider>;
  }

  return <>
      {arr.map((a, i) => <React.Fragment key={i}>
          {children(a, (val) => onChange(val === null ? arr.filter(b => b !== a) : arr.map(b => b === a ? val : b)), i)}
      </React.Fragment>)
      .concat(add === false ? [] : [ <React.Fragment key={(value && value.length) || 0}>
          {children(null, (val) => onChange(arr.concat([val])), (value && value.length) || 0)}
      </React.Fragment> ])}
  </>;
}
