import React, { createContext, useContext } from 'react';
import PropTypes from 'prop-types';
import { DragDropContext, Droppable } from 'react-beautiful-dnd';
import { useId } from '@reach/auto-id';

const propTypes = {
  /**
   * The FormList content. Must be composed of FormListItem to take full
   * advantage of the component.
   */
  children: PropTypes.node,

  /**
   * Event handler called on drag end. Check
   * https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/responders.md#ondragend-required
   * for more informations about the function signature.
   * If the event handler is not provided, the FormListItem won't be draggable.
   */
  onDragEnd: PropTypes.func,
};

const defaultProps = {
  children: '',
  onDragEnd: undefined,
};

export const FormListContext = createContext();
export const useFormListContext = () => useContext(FormListContext);

export const FormList = ({
  children,
  onDragEnd,
}) => {
  const id = useId();

  const renderChildren = () => {
    if (onDragEnd) {
      return (
        <DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId={`droppable-${id}`}>
            {(provided) => (
              <div
                ref={provided.innerRef}
                {...provided.droppableProps}
              >
                {children}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>
      );
    }

    return children;
  };

  return (
    <FormListContext.Provider value={{
      isDraggable: !!onDragEnd,
    }}
    >
      {renderChildren()}
    </FormListContext.Provider>
  );
};

FormList.propTypes = propTypes;
FormList.defaultProps = defaultProps;
