import {
  useClick,
  UseClickProps,
  useClientPoint,
  UseClientPointProps,
  useDismiss,
  UseDismissProps,
  useFocus,
  UseFocusProps,
  useHover,
  UseHoverProps,
  useInteractions,
  useListNavigation,
  UseListNavigationProps,
  useRole,
  UseRoleProps,
  useTypeahead,
  UseTypeaheadProps
} from '@floating-ui/react';
import React from 'react';
import { usePopoverContext } from '../NJPopoverContext';
import { NJPopoverInteractionContext } from '../NJPopoverInteractionContext';

export type NJPopoverInteractionsProps = React.PropsWithChildren & {
  hover?: UseHoverProps | true;
  focus?: UseFocusProps | true;
  click?: UseClickProps | true;
  role?: UseRoleProps;
  dismiss?: UseDismissProps | true;
  listNavigation?: UseListNavigationProps;
  typeahead?: UseTypeaheadProps;
  clientPoint?: UseClientPointProps;
};

export const NJPopoverInteractions: React.FC<NJPopoverInteractionsProps> = (props) => {
  const { context } = usePopoverContext();
  const interactions = [];

  if (props.hover) {
    interactions.push(useHover(context, typeof props.hover === 'object' ? props.hover : {}));
  }

  if (props.focus) {
    interactions.push(useFocus(context, typeof props.focus === 'object' ? props.focus : {}));
  }

  if (props.click) {
    interactions.push(useClick(context, typeof props.click === 'object' ? props.click : {}));
  }

  if (props.role) {
    interactions.push(useRole(context, props.role));
  }

  if (props.dismiss) {
    interactions.push(useDismiss(context, typeof props.dismiss === 'object' ? props.dismiss : {}));
  }

  if (props.listNavigation) {
    interactions.push(useListNavigation(context, props.listNavigation));
  }

  if (props.typeahead) {
    interactions.push(useTypeahead(context, props.typeahead));
  }

  if (props.clientPoint) {
    interactions.push(useClientPoint(context, props.clientPoint));
  }

  const interaction = useInteractions(interactions);
  return (
    <NJPopoverInteractionContext.Provider value={interaction}>
      {props.children}
    </NJPopoverInteractionContext.Provider>
  );
};
