import React, {
  memo,
  useCallback,
} from 'react';

import classNames from 'classnames';

import DropDown from '@enact/sandstone/Dropdown';

import { countryCode } from '../../api/apiConfig';
import useScrollReset from '../../hooks/useScrollReset';
import css from './TDropDown.module.less';

export default memo(function TDropDown({
  children,
  className,
  color,
  direction = "below",
  onClose,
  onOpen,
  onSelect,
  scrollTop,
  selectedIndex,
  size,
  width,
  ...rest
}) {
  const { handleScrollReset, handleStopScrolling } = useScrollReset(scrollTop);

  const _onOpen = useCallback(() => {
    if (onOpen) {
      onOpen();
    }
  }, [onOpen]);

  const _onClose = useCallback(() => {
    if (onClose) {
      onClose();
    }
  }, [onClose]);
  
  const _onSelect = useCallback((event) => {    
    if (onSelect) {
      onSelect({ selected: event.selected });
    }
  }, [onSelect]);  

  return (
    <DropDown
      className={classNames(
        css.tDropdown,
        css[size],
        css[color],
        selectedIndex !== undefined && selectedIndex !== null && css.selected,
        className
      )}
      direction={direction}
      selected={selectedIndex}
      onSelect={_onSelect}
      onFocus={handleScrollReset}
      onBlur={handleStopScrolling}
      onOpen={_onOpen}
      onClose={_onClose}
      style={width === 'small' ? { width: '240px', minWidth: '240px' } :
              width === 'medium' ? { width: '320px', minWidth: '320px' } :
              width === 'large' ? { width: '400px', minWidth: '400px' } : undefined}
      aria-disabled={countryCode && countryCode !== "US"}
      aria-label={children}
      {...rest}
    >
      {children}
    </DropDown>
  );
});