import React, { Component } from 'react';
import SortableTree, { ExtendedNodeData, TreeItem, NodeRenderer } from 'react-sortable-tree';
import { theme } from '@veeqo/ui';
import { IView } from 'types';
import Glyph from 'components/common/Glyph';

import defaultNodeContentRenderer from './nodeRenderer';

import View from './View';

import Container from './styled';

type ViewId = string;

export interface ViewTreeItem extends IView, TreeItem { }

export interface SortableViewsProps {
  views: IView[];
  onChange: (treeData: ViewTreeItem[]) => void;
  onClick?: (id: ViewId) => void;
  rowHeight?: number;
  nodeContentRenderer?: NodeRenderer;
  className?: string;
}

class SortableViews extends Component<SortableViewsProps> {
  generateNodeProps = ({ node }: ExtendedNodeData<any>) => {
    const { onClick } = this.props;

    return {
      moveHandle: (
        <Glyph name="drag-indicator" size="base" color={theme.colors.neutral.ink.base} />
      ),
      title: (
        <View onClick={onClick} id={`${node.id}`} label={node.label} isDefault={node.isDefault} />
      ),
    };
  };

  canNodeHaveChildren = () => false;

  render() {
    const {
      views,
      onChange,
      nodeContentRenderer = defaultNodeContentRenderer,
      rowHeight = 40,
      className,
      ...rest
    } = this.props;

    return (
      <Container height={views.length * rowHeight} className={className ? `${className}-sortable-views-container` : undefined}>
        <SortableTree
          className="sortableViews"
          rowHeight={rowHeight}
          treeData={views as any[]}
          canNodeHaveChildren={this.canNodeHaveChildren}
          onChange={onChange}
          generateNodeProps={this.generateNodeProps}
          isVirtualized={false}
          scaffoldBlockPxWidth={0}
          nodeContentRenderer={nodeContentRenderer}
          {...rest}
        />
      </Container>
    );
  }
}

export default SortableViews;
