import { useEffect } from 'react';
import useRestoreFocus from '@zohodesk/hooks/es/accessiblity/useRestoreFocus';
import useId from '@zohodesk/hooks/es/utils/useId';
import useAccessNavigationManager from '@zohodesk/hooks/es/accessiblity/useAccessNavigationManager';
import style from '../Select.module.css';
import useButtonAriaProps from '../../deprecated/button/useButtonAriaProps';

const useSelectAriaProps = function (props, state) {
  let config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    focus: true,
    wrap: true,
    hover: true,
    role: 'listbox',
    activeAnyOnEnter: true,
    activecss: style.focus3
  };
  const {
    uniqueId,
    isPopupOpen
  } = props || {};
  const labelUniqueNumber = uniqueId || useId();
  const navigationProps = useAccessNavigationManager(config);
  const {
    rootElementProps,
    getItemProps,
    focusFirst,
    onKeyDown,
    clearWhile
  } = navigationProps;
  const valueUniqueNumber = `${labelUniqueNumber}_valueid`;
  useRestoreFocus({
    isRestoreFocus: isPopupOpen,
    onUpdate: nodes => {
      focusFirst(); //state.selectedValue will be removed from list so, pass empty.

      return nodes;
    }
  });
  return {
    triggerProps: props => {
      const {
        focusClass,
        autoFocus
      } = props || {};
      const {
        buttonProps
      } = useButtonAriaProps({
        ariaLabelledby: uniqueId ? `${labelUniqueNumber} ${valueUniqueNumber}` : undefined,
        ariaHaspopup: 'listbox',
        ariaExpanded: isPopupOpen,
        focusClass,
        autoFocus,
        elementType: 'div'
      });
      return { ...buttonProps,
        onKeyDown
      };
    },
    labelProps: () => ({
      id: labelUniqueNumber
    }),
    valueProps: () => ({
      id: valueUniqueNumber
    }),
    menuProps: () => ({
      _role: 'listbox',
      // get role() {
      //     return this._role;
      // },
      // set role(value) {
      //     this._role = value;
      // },
      'aria-labelledby': labelUniqueNumber
    }),
    rootElementProps: () => ({ ...rootElementProps
    }),
    menuItemProps: props => {
      const {
        active,
        value,
        disabled,
        focusClass
      } = props || {};
      const {
        dataAriaItem,
        itemId,
        dataAriaItemDisabled
      } = getItemProps(value);
      const ariaItem = disabled ? dataAriaItemDisabled : dataAriaItem;
      return {
        role: 'option',
        id: `${labelUniqueNumber}_${value}`,
        tabIndex: !disabled ? '0' : '-1',
        'aria-selected': active,
        'aria-disabled': disabled ? 'true' : undefined,
        'data-aria-focusstyle': focusClass,
        ...ariaItem,
        itemId
      };
    }
  };
};

export default useSelectAriaProps;