import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import * as React from 'react';
import { getColumnPos, renderColumnTitle, getColumnKey } from '../../util';
import FilterDropdown from './FilterDropdown';

function collectFilterStates(columns, init, pos) {
  var filterStates = [];
  (columns || []).forEach(function (column, index) {
    var columnPos = getColumnPos(index, pos);

    if ('children' in column) {
      filterStates = [].concat(_toConsumableArray(filterStates), _toConsumableArray(collectFilterStates(column.children, init, columnPos)));
    } else if (column.filters || 'filterDropdown' in column || 'onFilter' in column) {
      if ('filteredValue' in column) {
        // Controlled
        var filteredValues = column.filteredValue;

        if (!('filterDropdown' in column)) {
          var _filteredValues$map, _filteredValues;

          filteredValues = (_filteredValues$map = (_filteredValues = filteredValues) === null || _filteredValues === void 0 ? void 0 : _filteredValues.map(String)) !== null && _filteredValues$map !== void 0 ? _filteredValues$map : filteredValues;
        }

        filterStates.push({
          column: column,
          key: getColumnKey(column, columnPos),
          filteredKeys: filteredValues,
          forceFiltered: column.filtered
        });
      } else {
        // Uncontrolled
        filterStates.push({
          column: column,
          key: getColumnKey(column, columnPos),
          filteredKeys: init && column.defaultFilteredValue ? column.defaultFilteredValue : undefined,
          forceFiltered: column.filtered
        });
      }
    }
  });
  return filterStates;
}

function injectFilter(prefixCls, dropdownPrefixCls, columns, filterStates, triggerFilter, getPopupContainer, locale, pos) {
  return columns.map(function (column, index) {
    var columnPos = getColumnPos(index, pos);
    var _column$filterMultipl = column.filterMultiple,
        filterMultiple = _column$filterMultipl === void 0 ? true : _column$filterMultipl;
    var newColumn = column;

    if (newColumn.filters || newColumn.filterDropdown) {
      var columnKey = getColumnKey(newColumn, columnPos);
      var filterState = filterStates.find(function (_ref) {
        var key = _ref.key;
        return columnKey === key;
      });
      newColumn = _objectSpread(_objectSpread({}, newColumn), {}, {
        title: function title(renderProps) {
          return /*#__PURE__*/React.createElement(FilterDropdown, {
            prefixCls: "".concat(prefixCls, "-filter"),
            dropdownPrefixCls: dropdownPrefixCls,
            column: newColumn,
            columnKey: columnKey,
            filterState: filterState,
            filterMultiple: filterMultiple,
            triggerFilter: triggerFilter,
            locale: locale,
            getPopupContainer: getPopupContainer
          }, renderColumnTitle(column.title, renderProps));
        }
      });
    }

    if ('children' in newColumn) {
      newColumn = _objectSpread(_objectSpread({}, newColumn), {}, {
        children: injectFilter(prefixCls, dropdownPrefixCls, newColumn.children, filterStates, triggerFilter, getPopupContainer, locale, columnPos)
      });
    }

    return newColumn;
  });
}

function flattenKeys(filters) {
  var keys = [];
  (filters || []).forEach(function (_ref2) {
    var value = _ref2.value,
        children = _ref2.children;
    keys.push(value);

    if (children) {
      keys = [].concat(_toConsumableArray(keys), _toConsumableArray(flattenKeys(children)));
    }
  });
  return keys;
}

function generateFilterInfo(filterStates) {
  var currentFilters = {};
  filterStates.forEach(function (_ref3) {
    var key = _ref3.key,
        filteredKeys = _ref3.filteredKeys,
        column = _ref3.column;
    var filters = column.filters,
        filterDropdown = column.filterDropdown;

    if (filterDropdown) {
      currentFilters[key] = filteredKeys || null;
    } else if (Array.isArray(filteredKeys)) {
      var keys = flattenKeys(filters);
      currentFilters[key] = keys.filter(function (originKey) {
        return filteredKeys.includes(String(originKey));
      });
    } else {
      currentFilters[key] = null;
    }
  });
  return currentFilters;
}

export function getFilterData(data, filterStates) {
  return filterStates.reduce(function (currentData, filterState) {
    var _filterState$column = filterState.column,
        onFilter = _filterState$column.onFilter,
        filters = _filterState$column.filters,
        filteredKeys = filterState.filteredKeys;

    if (onFilter && filteredKeys && filteredKeys.length) {
      return currentData.filter(function (record) {
        return filteredKeys.some(function (key) {
          var keys = flattenKeys(filters);
          var keyIndex = keys.findIndex(function (k) {
            return String(k) === String(key);
          });
          var realKey = keyIndex !== -1 ? keys[keyIndex] : key;
          return onFilter(realKey, record);
        });
      });
    }

    return currentData;
  }, data);
}

function useFilter(_ref4) {
  var prefixCls = _ref4.prefixCls,
      dropdownPrefixCls = _ref4.dropdownPrefixCls,
      mergedColumns = _ref4.mergedColumns,
      onFilterChange = _ref4.onFilterChange,
      getPopupContainer = _ref4.getPopupContainer,
      tableLocale = _ref4.locale;

  var _React$useState = React.useState(collectFilterStates(mergedColumns, true)),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      filterStates = _React$useState2[0],
      setFilterStates = _React$useState2[1];

  var mergedFilterStates = React.useMemo(function () {
    var collectedStates = collectFilterStates(mergedColumns, false); // Return if not controlled

    if (collectedStates.every(function (_ref5) {
      var filteredKeys = _ref5.filteredKeys;
      return filteredKeys === undefined;
    })) {
      return filterStates;
    }

    return collectedStates;
  }, [mergedColumns, filterStates]);
  var getFilters = React.useCallback(function () {
    return generateFilterInfo(mergedFilterStates);
  }, [mergedFilterStates]);

  var triggerFilter = function triggerFilter(filterState) {
    var newFilterStates = mergedFilterStates.filter(function (_ref6) {
      var key = _ref6.key;
      return key !== filterState.key;
    });
    newFilterStates.push(filterState);
    setFilterStates(newFilterStates);
    onFilterChange(generateFilterInfo(newFilterStates), newFilterStates);
  };

  var transformColumns = function transformColumns(innerColumns) {
    return injectFilter(prefixCls, dropdownPrefixCls, innerColumns, mergedFilterStates, triggerFilter, getPopupContainer, tableLocale);
  };

  return [transformColumns, mergedFilterStates, getFilters];
}

export default useFilter;