import _isEmpty from "lodash/fp/isEmpty";
import _includes from "lodash/fp/includes";
import _size from "lodash/fp/size";
import _isString from "lodash/fp/isString";
import _get from "lodash/fp/get";
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
import React, { useState } from 'react';
import classnames from 'classnames';
import ButtonLinkIcon from '../../atom/button-link-icon';
import StatusItem from '../../atom/status-item';
import BulkProgressBar from '../bulk-progress-bar';
import Provider, { GetTranslateFromContext } from '../../atom/provider';
import BulletPointMenuButton from '../bullet-point-menu-button';
import ButtonLink from '../../atom/button-link';
import ErrorsTable from '../errors-table';
import EmptySearchResult from '../../atom/empty-search-result';
import style from './style.css';
import { propTypes } from './types';
const buildField = field => {
  if (_isString(field)) return field;
  const {
    componentType
  } = field;
  switch (componentType) {
    case 'status':
      return /*#__PURE__*/React.createElement("div", {
        className: style.statusItemWrapper
      }, /*#__PURE__*/React.createElement(StatusItem, field));
    case 'progress-bar':
      return /*#__PURE__*/React.createElement(BulkProgressBar, field);
  }
};
const buildLastField = lastField => {
  const {
    componentType
  } = lastField;
  switch (componentType) {
    case 'menu':
      return /*#__PURE__*/React.createElement(BulletPointMenuButton, lastField);
    case 'button-link':
      return /*#__PURE__*/React.createElement(ButtonLink, lastField);
  }
};
const buildNestedRow = row => {
  const {
    componentType
  } = row;
  switch (componentType) {
    case 'errors-table':
      return /*#__PURE__*/React.createElement(ErrorsTable, row);
    case 'expandible-errors-table':
      return /*#__PURE__*/React.createElement(ActionableExpandableTable, row);
  }
};
const ActionableExpandableTable = (props, legacyContext) => {
  const {
    columns,
    rows = [],
    lastField,
    stickyFirstColumn = false,
    stickyLastColumn = false,
    ariaDescribedby,
    columnWidth = `${100 / _size(columns)}%`,
    isNestedTable = false,
    emptyStateFistMessage = '',
    emptyStateSecondMessage = ''
  } = props;
  const translate = GetTranslateFromContext(legacyContext);

  /**
   * State variable to keep track of all the expanded rows
   * By default, nothing expanded. Hence initialized with empty array.
   */
  const [expandedRows, setExpandedRows] = useState([]);

  /**
   * State variable to keep track which row is currently expanded.
   */
  const [expandState, setExpandState] = useState({});
  if (_isEmpty(columns)) return /*#__PURE__*/React.createElement("div", {
    className: style.wrapper
  }, /*#__PURE__*/React.createElement(EmptySearchResult, {
    firstMessage: emptyStateFistMessage,
    secondMessage: emptyStateSecondMessage,
    isBulk: true
  }));

  /**
   * This function gets called when show/hide link is clicked.
   */
  const handleExpandRow = index => () => {
    const isRowExpanded = _includes(index, expandedRows);

    /**
     * If the row is expanded, we are here to hide it. Hence remove
     * it from the state variable. Otherwise add to it.
     */
    const newExpandedRows = isRowExpanded ? expandedRows.filter(id => id !== index) : expandedRows.concat(index);
    setExpandedRows(newExpandedRows);

    /**
     * Create a new object to update the expanded state of all rows
     * Use the newExpandedRows array to set the state of all rows that are currently expanded
     */
    const expandedState = {};
    newExpandedRows.forEach(id => {
      expandedState[id] = true;
    });
    setExpandState(expandedState);
  };
  const headerRow = columns.map((column, cIndex) => {
    const {
      title
    } = column;
    return /*#__PURE__*/React.createElement("th", {
      className: cIndex === 0 ? classnames(stickyFirstColumn ? style.headerFirstSticky : style.headerFirst, style.header) : style.header,
      key: `${title}-${cIndex}`,
      role: "columnheader"
    }, title);
  });
  headerRow.push(/*#__PURE__*/React.createElement("th", {
    className: stickyLastColumn ? style.headerLastSticky : style.headerLast,
    key: "action-header"
  }));
  const headerView = [...headerRow];
  const bodyView = rows.map((row, index) => {
    const {
      fields,
      isRowExpandible = false
    } = row;
    const bodyRow = fields.map((field, fIndex) => {
      const cellContent = fIndex === 0 ? /*#__PURE__*/React.createElement("div", {
        className: style.columFirstWrapper
      }, /*#__PURE__*/React.createElement("div", {
        className: style.expandButtonWrapper
      }, isRowExpandible ? /*#__PURE__*/React.createElement(ButtonLinkIcon, {
        onClick: handleExpandRow(index),
        "data-name": `arrowUp-button-${index}`,
        icon: "down",
        className: expandState[index] ? 'bulkArrowUp' : 'bulkArrowDown',
        "aria-label": translate('bulk_import.show_errors')
      }) : null), buildField(field)) : buildField(field);
      return /*#__PURE__*/React.createElement("td", {
        className: fIndex === 0 ? classnames(stickyFirstColumn ? style.columnFirstSticky : style.columnFirst, style.col) : style.col,
        style: {
          width: columnWidth
        },
        key: `${field}-${fIndex}`
      }, cellContent);
    });
    bodyRow.push(/*#__PURE__*/React.createElement("td", {
      className: stickyLastColumn ? style.columnLastSticky : style.columnLast,
      key: "actionHeader"
    }, lastField ? /*#__PURE__*/React.createElement("div", {
      className: classnames({
        [style.inspectButton]: _get('className', lastField) === 'bulkInspectButton'
      })
    }, buildLastField(lastField)) : null));
    const nestedRow = _get('nestedRow', row);
    const nestedRowCellule = nestedRow && expandedRows.includes(index) ? /*#__PURE__*/React.createElement("tr", {
      key: `line-${index}-error`
    }, /*#__PURE__*/React.createElement("td", {
      className: style.nestedRowCellule,
      colSpan: fields.length + 2
    }, buildNestedRow(nestedRow))) : null;
    return nestedRowCellule ? [/*#__PURE__*/React.createElement("tr", {
      key: `line-${index}`
    }, bodyRow), nestedRowCellule] : [/*#__PURE__*/React.createElement("tr", {
      key: `line-${index}`
    }, bodyRow)];
  });
  return /*#__PURE__*/React.createElement("div", {
    className: style.wrapper
  }, /*#__PURE__*/React.createElement("table", _extends({}, ariaDescribedby ? {
    'aria-describedby': ariaDescribedby
  } : {}, {
    className: style.table,
    "data-testid": "expandible-actionable-table",
    "data-name": "expandible-actionable-table"
  }), /*#__PURE__*/React.createElement("thead", {
    className: isNestedTable ? style.theadNested : style.thead
  }, /*#__PURE__*/React.createElement("tr", null, headerView)), /*#__PURE__*/React.createElement("tbody", null, bodyView)));
};
ActionableExpandableTable.contextTypes = {
  skin: Provider.childContextTypes.skin,
  translate: Provider.childContextTypes.translate
};
ActionableExpandableTable.propTypes = process.env.NODE_ENV !== "production" ? propTypes : {};
export default ActionableExpandableTable;
//# sourceMappingURL=index.js.map