import React, { useState } from 'react';
import { on_select, on_remove, filter_for_search, on_remove_all, on_select_all, add, filter_options_check } from '../utils/MultiSelect.manage';
import useCommonReducer from '../../../libraries/reducerHandler';
import constants from '../actions/MultiSelect.actionConstants';
import multiSelectStateReducers from '../actions/MultiSelect.action';
export default function useMultiSelectWithSearch(props, reducer) {
  const {
    state = {},
    dispatch
  } = useCommonReducer(multiSelectStateReducers, props.reducer, {
    searchString: '',
    selectedSuggestions: [],
    filteredOptions: [],
    list: []
  });

  function onHandleSelect(value) {
    state.selectedSuggestions.push(value);
    state.searchString = '';
    const newState = { ...state
    };
    dispatch({
      type: constants.ON_MULTISELECT_SELECT,
      data: newState
    });
  }

  function addOptions(obj) {
    add(obj, state);
    dispatch({
      type: constants.ON_MULTISELECT_ADD,
      data: state
    });
  }

  function get_filtered_options_data() {
    return state.filteredOptions;
  }

  function filterOptionsCheck(value) {
    return filter_options_check(value, state.filteredOptions);
  }

  function updateSelectedValues(value) {
    dispatch({
      type: constants.ON_MULTISELECT_UPDATE_SELECTED_VALUES,
      data: value
    });
  }

  function onHandleRemove(value) {
    on_remove(value, state);
    const selected_suggestions = state.selectedSuggestions;
    const newState = { ...state,
      selectedSuggestions: selected_suggestions
    };
    dispatch({
      type: constants.ON_MULTISELECT_REMOVE,
      data: newState
    });
  }

  function onShortcutKeys(e) {
    const {
      keyCode,
      ctrlKey,
      metaKey,
      shiftKey
    } = e;

    if (keyCode === 8 || keyCode === 46) {
      let selected_suggestions = state.selectedSuggestions;
      const searchString = state.searchString;

      if (!(searchString.length > 0)) {
        const index = selected_suggestions.findIndex((ele, i) => {
          const des = document.querySelector("[aria-activedescendant]") ? document.querySelector("[aria-activedescendant]").getAttribute('aria-activedescendant') : null;

          if (ele === des) {
            return i;
          }
        });
        const val = index === -1 ? selected_suggestions.pop() : selected_suggestions[index];
        console.log(val, 'val');
        on_remove(val, state);
        selected_suggestions = state.selectedSuggestions;
        dispatch({
          type: constants.ON_MULTISELECT_REMOVE,
          data: state
        });
      }
    }
  }

  function onSearch(str) {
    dispatch({
      type: constants.ON_MULTISELECT_SEARCH,
      data: { ...state,
        searchString: str
      }
    });
  }

  function onEnterClick(value) {
    const isvalidation = props.onValidation({
      value,
      selectedSuggestions: state.selectedSuggestions
    });

    if (value.length && state.selectedSuggestions.indexOf(value) === -1 && !props.limit && isvalidation) {
      onHandleSelect(value);
    } else {
      isvalidation && !(state.selectedSuggestions.length === props.limit) && value.length && state.selectedSuggestions.indexOf(value) === -1 && onHandleSelect(value);
    }
  }

  function onKeyDown(e) {
    if (e.keyCode === 13) {
      onEnterClick(e.target.value);
    } else if (e.keyCode === 188) {
      onEnterClick(state.searchString);
    }
  }

  function onPaste(e) {
    debugger;
    const value = e.clipboardData.getData('Text') || '';
    const convertedValue = value.split(',');
    convertedValue.length && convertedValue.forEach(val => {
      onEnterClick(val);
    });
  }

  return {
    filteredOptions: state.filteredOptions,
    updateSelectedValues,
    onShortcutKeys,
    addOptions,
    list: state.list,
    selectedValues: state.selectedSuggestions,
    onHandleSelect,
    onHandleRemove,
    onSearch,
    onKeyDown,
    onPaste,
    searchString: state.searchString,
    getFilteredOptionsData: get_filtered_options_data,
    filterOptionsCheck
  };
}