import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import TableRowColumn from './TableRowColumn';

import './table.scss';

class TableRow extends PureComponent {
  static propTypes = {
    /**
     * Children passed to table row.
     */
    children: PropTypes.node,
    /**
     * @ignore in documentation
     * Controls the display of the row checkbox.
     * is automatically populated when used with TableBody.
     */
    displayRowCheckbox: PropTypes.bool,
    /**
     * @ignore in documentation
     * Controls the display of the row to adjust checkbox.
     * is automatically populated when used with TableHeader or TableFooter.
     */
    adjustForCheckbox: PropTypes.bool,
    /**
     * @ignore
     * Called when a row cell is clicked.
     * rowNumber is the row number and columnId is
     * the column number or the column key.
     */
    onCellClick: PropTypes.func,
    /**
     * @ignore
     * Called when row is clicked.
     */
    onRowClick: PropTypes.func,
    /**
     * Number to identify the row. This property is
     * automatically populated when used with the TableBody component.
     */
    rowNumber: PropTypes.number,
    /**
     * If true, table rows can be selected. If multiple row
     * selection is desired, enable multiSelectable.
     * The default value is true.
     */
    selectable: PropTypes.bool,
    /**
     * Indicates that a particular row is selected.
     * This property can be used to programmatically select rows.
     */
    selected: PropTypes.bool,
    multiSelectable: PropTypes.bool,
    sortedField: PropTypes.array,
    order: PropTypes.string,
    white: PropTypes.bool,
    grey: PropTypes.bool,
    className: PropTypes.string
  };

  static defaultProps = {
    children: null,
    hoverable: false,
    onCellClick: null,
    onRowClick: null,
    rowNumber: null,
    selectable: false,
    displayRowCheckbox: false,
    adjustForCheckbox: false,
    selected: false,
    multiSelectable: false,
    sortedField: null,
    order: null,
    white: false,
    grey: false,
    className: undefined
  };

  onRowClick(event) {
    if (this.props.selectable && this.props.onRowClick) {
      this.props.onRowClick(event, this.props.rowNumber);
    }
  }

  onCellClick = (event, props) => {
    const { rowNumber } = this.props;
    if (this.props.onCellClick) {
      this.props.onCellClick(event, { ...props, rowNumber });
    }
    this.onRowClick({ ...event });
  };

  onCheckboxClick = event => {
    this.onRowClick({ ...event, ctrlKey: true });
    event.stopPropagation();
  };

  onCheckboxChange = event => {
    event.stopPropagation();
  };

  render() {
    const {
      rowNumber,
      displayRowCheckbox,
      adjustForCheckbox,
      selected, // , eslint-disable-line no-unused-vars
      selectable,
      multiSelectable,
      sortedField,
      order,
      white,
      grey,
      className
    } = this.props;
    const rowColumns = (displayRowCheckbox || adjustForCheckbox) ? [(
      <TableRowColumn checkbox>
        {displayRowCheckbox
          && <input
            type="checkbox"
            checked={selected}
            onClick={this.onCheckboxClick}
            onChange={this.onCheckboxChange}
          />}
      </TableRowColumn>
    )] : [];
    const rowColumnsResult = rowColumns
      .concat(React.Children.toArray(this.props.children))
      .map((child, columnNumber) => (
        React.isValidElement(child) ?
          React.cloneElement(child, {
            key: `${rowNumber}-${columnNumber}`, // eslint-disable-line react/no-array-index-key
            onClick: this.onCellClick,
            selected,
            columnNumber,
            selectable,
            multiSelectable,
            sortedOrder: sortedField === child.props.sort ? order : null
          }) : null
      ));

    return (
      <tr
        className={className}
        styleName={classNames(
          'table-row',
          { 'table-row--selected': selected },
          { white },
          { grey }
        )}
      >
        {rowColumnsResult}
      </tr>
    );
  }
}

export function createRow({ child, isRowSelected, props, index, rowNumber = 0 }) {
  const { onRowClick, onCellClick, ...rest } = props || {};
  const resultProps = {
    key: `f-${rowNumber}`,
    selected: typeof isRowSelected === 'function' ? isRowSelected(index) : false,
    index,
    ...rest,
    rowNumber
  };
  if (child) {
    if (onRowClick) {
      resultProps.onRowClick = (event, row) => {
        onRowClick(event, row);
        if (child.props.onRowClick) {
          child.props.onRowClick(event, row);
        }
      };
    }
    if (onCellClick) {
      resultProps.onCellClick = (event, row, columnIndex) => {
        onCellClick(event, row, columnIndex);
        if (child.props.onCellClick) {
          child.props.onCellClick(event, row);
        }
      };
    }
    if (React.isValidElement(child)) {
      return React.cloneElement(child, resultProps);
    }
  }
  return null;
}

export function createRows({ children, isRowSelected, props }) {
  let rowNumber = 0;
  return React.Children.map(children, child => {
    const resultChild = createRow({ child, isRowSelected, props, rowNumber });
    if (resultChild) {
      rowNumber += 1;
    }
    return resultChild;
  });
}

export default TableRow;
