import { Checkbox } from '@wix/design-system';
import React from 'react';
import { FiltersMap } from '@wix/bex-core';
import { observer } from 'mobx-react-lite';
import { PickerContentState } from '../../state';

export interface SelectAllCheckboxProps<T, F extends FiltersMap> {
  state: PickerContentState<T, F>;
}

function _SelectAllCheckbox<T, F extends FiltersMap>(
  props: SelectAllCheckboxProps<T, F>,
) {
  const { state } = props;
  const {
    toggleIsSelectAll,
    picker: {
      collection: {
        result: { isEmptyAndNotFetching },
        query: { hasActiveFilters, limit },
        bulkSelect: {
          selectedCountOrTotal,
          select: { isNotEmptyEnabledItems: hasEnabledCheckedItems },
          allSelected,
          hasUnchecked,
          collection: {
            result: { total },
          },
        },
        translate: t,
      },
    },
  } = state;
  return (
    <Checkbox
      dataHook="picker-select-all-checkbox"
      checked={allSelected}
      disabled={isEmptyAndNotFetching || (hasActiveFilters && total > limit)}
      onChange={toggleIsSelectAll}
      indeterminate={hasEnabledCheckedItems && (!allSelected || hasUnchecked)}
    >
      {hasEnabledCheckedItems ? (
        <>
          {t('cairo.deselectAll')} ({selectedCountOrTotal})
        </>
      ) : (
        <>
          {t('cairo.selectAll')} ({total})
        </>
      )}
    </Checkbox>
  );
}

export const SelectAllCheckbox = observer(_SelectAllCheckbox);
