/**
 * TEAM: frontend_infra
 * @flow strict
 */

import * as React from "react";
import {StyleSheet, css} from "aphrodite";
import SelectionList, {type SelectionListInstance} from "./SelectionList";
import SelectionListOption from "./SelectionListOption";
import Dropdown, {type DropdownInstance} from "../Dropdown";

export const DEFAULT_MAX_HEIGHT = 320;

type Props = {|
  /** The content for the list to display */
  +children: React.Node,
  /** The value of the selected list option */
  +selected?: ?string,
  /** called when a dropdown option is clicked */
  +onSelection: (selected: string) => void,
  /** Parent of the dropdown, interacting with this element will open, close, and affect the dropdown. */
  +parent: React.Node,
  /** The max height of the dropdown displayed before scrolling */
  +maxHeight?: number,
  /** Hide the dropdown when an item is selected. */
  +hideOnSelection?: boolean,
  /** Callback when dropdown opens */
  +onOpen?: () => void,
  /** Callback when dropdown closes */
  +onClose?: () => void,
|};

/**
 * @category Data Entry
 * @short A selection list attached to a given parent, includes unified focus state and keyboard support.
 * @brandStatus V2
 * @status In Review
 */
function DropdownListExperimental({
  selected,
  onSelection,
  children,
  parent,
  maxHeight = DEFAULT_MAX_HEIGHT,
  hideOnSelection = false,
  onOpen,
  onClose,
}: Props): React.Element<typeof Dropdown> {
  const selectionList = React.useRef<?SelectionListInstance>();
  const dropdown = React.useRef<?DropdownInstance>();
  const onSelectionHandler = React.useCallback(
    selected => {
      if (hideOnSelection && dropdown.current) {
        dropdown.current.hide();
      }

      onSelection(selected);
    },
    [hideOnSelection, onSelection]
  );

  return (
    <Dropdown
      parent={parent}
      onKeyDown={e => {
        if (selectionList.current != null)
          selectionList.current.parseKeyEvent(e);
      }}
      onOpen={onOpen}
      onClose={onClose}
      ref={dropdown}
    >
      <div className={css(styles.dropdown)} style={{maxHeight}}>
        <div className={css(styles.list)}>
          <SelectionList
            selected={selected}
            onSelection={onSelectionHandler}
            ref={selectionList}
          >
            {children}
          </SelectionList>
        </div>
      </div>
    </Dropdown>
  );
}

DropdownListExperimental.Option = SelectionListOption;

export default DropdownListExperimental;

const styles = StyleSheet.create({
  dropdown: {
    display: "flex",
    flexDirection: "column",
    overflow: "auto",
  },
  list: {
    overflow: "auto",
    position: "relative",
    flex: "1 1 auto",
  },
});
