import * as React from 'react';

import { MmuiProps, MmuiState, MmuiCommonComponent } from '../common';

/**
 * Selection Filter UI Component
 */
export class MmuiSelectionFilterComponent<
  P extends MmuiProps,
  S extends MmuiState
> extends MmuiCommonComponent<P, S> {
  constructor(props) {
    super(props);
  }

  /**
   * @return this component's initial state.
   */
  getInitialComponentState(): any {
    const state = {
      mode: '',
      isVisible: false,
      selectedRowIds: [],
      sourceUpdatedAt: null,
    };

    return state;
  }

  componentDidUpdate(): void {
    const componentState = this.getComponentState();

    if (componentState.operation === 'update') {
      const selectedRowIds = this.props.store.shared.selectedRowIds;

      this.setComponentState({
        isVisible: selectedRowIds.length > 0,
        numSelected: selectedRowIds.length,
        operation: '',
      });
    }
  }

  /**
   * On Filter Event Listener
   * @param e
   */
  onFilter = (e) => {
    e.preventDefault();
    this.props.setToStore(['shared', 'operation'], 'filter_apply');
  };

  /**
   * * On Filter Event Listener
   * @param e
   */
  onClear = (e) => {
    e.preventDefault();
    this.props.setToStore(['shared', 'operation'], 'filter_clear');
  };

  render() {
    const componentState = this.getComponentState();

    if (
      componentState === undefined ||
      componentState === null ||
      !componentState.isVisible
    ) {
      return null;
    }

    return (
      <div className="d-flex mmui-mb-3">
        <div className="align-self-center mmui-mr-2">
          {componentState.numSelected} Selected
        </div>
        <div className="align-self-center">
          <a href="#" onClick={this.onClear}>
            Clear Selection
          </a>
        </div>
        <div className="mmui-ml-2">
          <a
            role="button"
            className="btn mmui-link-button"
            href="#"
            onClick={this.onFilter}
          >
            filter
          </a>
        </div>
      </div>
    );
  }
}
