"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = withTableCellCheckboxes;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _checkbox = require("../../../checkbox");
var _useCheckboxCellsState = require("../../hooks/use-checkbox-cells-state");
var _useTranslation = require("../../../hooks/use-translation");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/**
 * Wrapper around base table to add checkboxes column
 * @param {React.Component} BaseTable - table to wrap
 * @param {
 *   headerCheckboxTestId {string} - test-id to be passed to header checkbox
 *   bodyRowCheckboxTestId {string} - test-id to be passed to table row checkbox
 * @returns React.Component;
 */
function withTableCellCheckboxes(BaseTable, {
  headerCheckboxTestId = 'header-selection-checkbox',
  bodyRowCheckboxTestId = 'row-selection-checkbox'
} = {}) {
  function WithTableCellCheckboxes({
    forwardRef,
    columns,
    className = '',
    data,
    checkboxAccessor,
    onUpdateSelection,
    headerCheckboxWrapper,
    checkboxHeaderClassName,
    checkboxCellClassName,
    checkboxSelectAllAriaLabel,
    checkboxSelectRowAriaLabel,
    ...props
  }) {
    const {
      t
    } = (0, _useTranslation.useTranslation)();
    const {
      items: checkboxItems,
      areAllChecked,
      areSomeChecked,
      setCheckboxItems
    } = (0, _useCheckboxCellsState.useCheckboxCellsState)(data?.map(item => !!item[checkboxAccessor]));
    (0, _react.useEffect)(() => {
      setCheckboxItems(data?.map(proj => !!proj[checkboxAccessor]));
    }, [data]);
    function BodyCell({
      row,
      index,
      testId = bodyRowCheckboxTestId
    }) {
      const id = row.pid || index.toString();
      function onCheckboxUpdate() {
        const updatedValues = checkboxItems.map((item, idx) => index === idx ? !item : item);
        setCheckboxItems(updatedValues);
        onUpdateSelection({
          updatedData: data?.map((item, idx) => ({
            ...item,
            [checkboxAccessor]: updatedValues[idx]
          })),
          updatedCheckboxValues: updatedValues
        });
      }
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        "test-id": testId,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_checkbox.Checkbox, {
          isDisabled: row.isDisabled,
          indeterminate: row.isDisabled,
          isChecked: checkboxItems[index],
          onChange: onCheckboxUpdate,
          id: id,
          ariaLabel: checkboxSelectRowAriaLabel?.(row) || t('Select {{val}}', {
            val: Object.values(row)[1]
          })
        }, id)
      });
    }
    function HeaderCell({
      testId = headerCheckboxTestId
    }) {
      const areNoneChecked = !areAllChecked && !areSomeChecked;
      const areAllDisabled = data?.every(item => item.isDisabled);
      const onChange = () => {
        const updatedValues = checkboxItems.map((item, index) => data?.[index].isDisabled ? data[index][checkboxAccessor] : areNoneChecked);
        setCheckboxItems(updatedValues);
        onUpdateSelection({
          updatedData: data?.map((item, idx) => ({
            ...item,
            [checkboxAccessor]: updatedValues[idx]
          })),
          updatedCheckboxValues: updatedValues
        });
      };
      const headerCell = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        "test-id": testId,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_checkbox.Checkbox, {
          isDisabled: areAllDisabled,
          isChecked: areAllChecked,
          indeterminate: areSomeChecked || areAllDisabled,
          onChange: onChange,
          id: "table-with-checkboxes-main-checkbox",
          ariaLabel: checkboxSelectAllAriaLabel ?? t('Select all rows')
        })
      });
      return headerCheckboxWrapper ? headerCheckboxWrapper(headerCell) : headerCell;
    }
    const checkboxColumn = {
      header: HeaderCell,
      cell: BodyCell,
      id: 'checkbox-cell',
      // disabled property is needed since otherwise the checkbox cell could be sortable
      // it does not disable the checkbox
      disabled: true
    };
    if (checkboxHeaderClassName) {
      checkboxColumn.headerClassName = checkboxHeaderClassName;
    }
    if (checkboxCellClassName) {
      checkboxColumn.cellClassName = checkboxCellClassName;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(BaseTable, {
      ref: forwardRef,
      ...props,
      data: data,
      columns: [checkboxColumn, ...columns],
      className: (0, _classnames.default)('table-with-checkboxes', {
        [className]: !!className
      })
    });
  }
  WithTableCellCheckboxes.defaultProps = {
    onUpdateSelection: () => {},
    checkboxAccessor: 'selected'
  };
  const WithRefTableCellCheckboxes = /*#__PURE__*/_react.default.forwardRef((props, ref) => /*#__PURE__*/(0, _jsxRuntime.jsx)(WithTableCellCheckboxes, {
    ...props,
    forwardRef: ref
  }));
  WithRefTableCellCheckboxes.displayName = 'WithTableCellCheckboxes';
  return WithRefTableCellCheckboxes;
}