import React, { useEffect } from 'react';
import cx from 'classnames';
import { Checkbox } from '../../../checkbox';
import { useCheckboxCellsState } from '../../hooks/use-checkbox-cells-state';
import { useTranslation } from '../../../hooks/use-translation';
import { jsx as _jsx } from "react/jsx-runtime";
/**
 * 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;
 */
export default 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
    } = useTranslation();
    const {
      items: checkboxItems,
      areAllChecked,
      areSomeChecked,
      setCheckboxItems
    } = useCheckboxCellsState(data?.map(item => !!item[checkboxAccessor]));
    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__*/_jsx("div", {
        "test-id": testId,
        children: /*#__PURE__*/_jsx(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__*/_jsx("div", {
        "test-id": testId,
        children: /*#__PURE__*/_jsx(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__*/_jsx(BaseTable, {
      ref: forwardRef,
      ...props,
      data: data,
      columns: [checkboxColumn, ...columns],
      className: cx('table-with-checkboxes', {
        [className]: !!className
      })
    });
  }
  WithTableCellCheckboxes.defaultProps = {
    onUpdateSelection: () => {},
    checkboxAccessor: 'selected'
  };
  const WithRefTableCellCheckboxes = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/_jsx(WithTableCellCheckboxes, {
    ...props,
    forwardRef: ref
  }));
  WithRefTableCellCheckboxes.displayName = 'WithTableCellCheckboxes';
  return WithRefTableCellCheckboxes;
}