import './TableTree.scss';
import Icon from '../Icon/Icon.js';
import Checkbox from '../Checkbox/Checkbox.js';
import classNames from 'classnames';

interface ColumnDataProps {
  name: string;
  accessor: string;
  width: string;
  isClickable?: boolean;
}

interface ObjectProps {
  [key: string]: any;
}

interface TableTreeProps {
  withCheckBox: boolean;
  columnsData: Array<ColumnDataProps>;
  treeData: Array<ObjectProps>;
  onClick?: (
    event: React.MouseEvent<HTMLDivElement, MouseEvent>,
    data: any
  ) => void;
}

const TableTree = ({
  withCheckBox,
  columnsData,
  treeData,
  onClick = () => {},
}: TableTreeProps) => {
  const renderTree = (tree: Array<ObjectProps>, i: number) => {
    if (tree?.length > 0) {
      return (
        <ul className="ul">
          {tree.map((node) => {
            const folder = node.folder ? 'folder' : '';

            return (
              <li className={`node-${i}`}>
                <span className="node">
                  <span className="title-container">
                    {folder && (
                      <span className="folder">
                        {i !== 0 && (
                          <Icon name="arrow_down" height={12} width={12} />
                        )}
                        {withCheckBox && (
                          <span>
                            <Checkbox
                              style={{ height: '16px', width: '16px' }}
                            />
                          </span>
                        )}
                      </span>
                    )}
                    <div
                      onClick={(e) => onClick(e, { name: 'title', node })}
                      className={classNames(`title--${folder}`, {
                        'title--pointer': onclick,
                      })}
                    >
                      {node.title}
                    </div>
                  </span>

                  {columnsData.map((column: ColumnDataProps) => (
                    <div
                      style={{ width: column.width }}
                      className={classNames('column', {
                        'column--pointer': column.isClickable,
                      })}
                      onClick={(e) =>
                        column.isClickable ? onClick(e, { column, node }) : null
                      }
                    >
                      {i !== 0 ? (
                        node[column.accessor]
                      ) : (
                        <span className="columnHeading">{column.name}</span>
                      )}
                    </div>
                  ))}
                </span>
                {node?.children?.length > 0 && renderTree(node.children, i + 1)}
              </li>
            );
          })}
        </ul>
      );
    }
  };

  return (
    <div className="tree-container">
      <div className="tree">{renderTree(treeData, 0)}</div>
    </div>
  );
};

export default TableTree;
