import * as React from 'react';
import * as classNames from 'classnames';
import {CSSProperties, SFC, HTMLProps, Ref} from 'react';
import {Icon, Scrollbars} from './../';
import {ColumnHeaderProperty, SortProperty} from './models';
import {getSortProperty, isSortDescending} from './utils/string';

export interface TableProps extends HTMLProps<HTMLElement> {
  properties: ColumnHeaderProperty[];
  sort: string;
  tableMinWidth: number;
  onSort: (property: string) => void;
}

let scrollbars: Scrollbars;

export const DatagridTable: SFC<TableProps> = (props: TableProps) => {
  const {children, tableMinWidth} = props;
  const style = {minWidth: tableMinWidth};

  return (
    <div className="bkn-data-grid-table">
      <Scrollbars>
        <div className="grid-table" style={style}>
          <div className="grid-thead">
            <div className="grid-tr">
              {renderHeaders(props)}
            </div>
          </div>

          {children}
        </div >
      </Scrollbars>
    </div >
  );
};

DatagridTable.displayName = 'DatagridTable';

const renderHeaders = (props: TableProps) => {
  const {properties, sort} = props;

  return properties.map((p, index) => (
    <div
      key={index}
      className={classNames(
        'grid-th',
        {
          active: getSortProperty(sort) === p.sortKey,
          asc: p.sortKey && sort.indexOf('-') !== 0,
          desc: p.sortKey && sort.indexOf('-') === 0,
          'no-sort': !p.sortKey,
        },
      )}
      style={p.thStyle}
      onClick={handleSortInfo(props, p.sortKey)}
    >
      <span>{p.name}</span>
      {p.sortKey && <Icon className="sort-icon" name="arrow_upward" />}
    </div>
  ));
};

const handleSortInfo = (props: TableProps, columnPropertyKey: string) => () => {
  if (!columnPropertyKey) { return; }

  const hasToSortSameColumn = getSortProperty(props.sort) === columnPropertyKey;

  if (hasToSortSameColumn) {
    props.onSort(invertSortingDirection(props.sort));
    return;
  }

  props.onSort(columnPropertyKey);
};

const invertSortingDirection = (property: string) => {
  return isSortDescending(property)
    ? property.substr(1)
    : `-${property}`;
};
