import { callAllHandlers, clsx } from '@trail-ui/shared-utils';
import React, { ForwardedRef, forwardRef, useContext } from 'react';
import { OverlayTriggerStateContext } from 'react-aria-components';
import { CloseButton, CloseButtonProps } from '../button';

import { InternalModalContext } from './modal';
import { OverlayTriggerState } from 'react-stately';

function ModalCloseButton(props: CloseButtonProps, ref: ForwardedRef<HTMLButtonElement>) {
  const { children, className, onPress, ...otherProps } = props;
  const state = useContext<OverlayTriggerState | null>(OverlayTriggerStateContext);
  const { slots, classNames } = useContext(InternalModalContext);

  return (
    <CloseButton
      ref={ref}
      className={slots.closeButton({ class: clsx(classNames?.closeButton, className) })}
      onPress={callAllHandlers(onPress, () => state?.close())}
      appearance="transparent"
      spacing="compact"
      {...otherProps}
    >
      {children}
    </CloseButton>
  );
}

const _ModalCloseButton = forwardRef(ModalCloseButton);

export { _ModalCloseButton as ModalCloseButton };
