import React from 'react';
import classNames from 'classnames';
import { Droppable, Draggable } from 'react-beautiful-dnd';
import LayerItem from './LayerItem';
import LayerGroup from './LayerGroup';
import styles from './LayerList.less';

export default function LayerList({ draggableId, layers, onSelect, onChange, resetLayers }) {
  const renderItem = (item, index, level, type) => {
    return (
      item?.id && (
        <Draggable key={item.id} draggableId={item.id} type={type} index={index}>
          {(provided) => (
            <LayerItem
              data={item}
              level={level}
              selected={item.selected}
              provided={provided}
              draggableId={draggableId}
              onSelect={onSelect}
              onChange={onChange}
            />
          )}
        </Draggable>
      )
    );
  };

  const renderList = (list, level = 0) => {
    return (
      <Droppable droppableId={`${list.id}`} key={list.id} type={list.id}>
        {(dropProvided) => (
          <div
            className={classNames(styles.list, { [styles.collapsed]: list.collapsed })}
            ref={dropProvided.innerRef}
            {...dropProvided.droppableProps}
            onClick={level === 0 && !draggableId ? resetLayers : null}>
            {level > 0 && (
              <LayerGroup
                id={list.id}
                name={list.name}
                show={list.show}
                lock={list.lock}
                level={level - 1}
                draggableId={draggableId}
                collapsed={list.collapsed}
                selected={list.selected}
                onSelect={onSelect}
                onChange={onChange}
              />
            )}
            {list.components.map((item, index) => {
              if (!item.components) {
                return renderItem(item, index, level, list.id);
              } else {
                return (
                  <Draggable draggableId={item.id} key={item.id} index={index} type={list.id}>
                    {(dragProvided) => (
                      <div
                        ref={dragProvided.innerRef}
                        {...dragProvided.draggableProps}
                        {...dragProvided.dragHandleProps}>
                        {renderList(item, level + 1)}
                      </div>
                    )}
                  </Draggable>
                );
              }
            })}
            {dropProvided.placeholder}
          </div>
        )}
      </Droppable>
    );
  };

  const decData = (data = []) => {
    return {
      id: 'top',
      name: 'top',
      show: true,
      components: data,
    };
  };

  return renderList(decData(layers));
}
