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

import { InternalModalContext } from './modal';
import { OverlayTriggerState } from 'react-stately';
import { mergeRefs } from '@trail-ui/hooks';

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

  useEffect(() => {
    if (state?.isOpen) localRef.current?.focus();
  }, [state?.isOpen]);

  return (
    <CloseButton
      ref={mergeRefs(ref, localRef)}
      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 };
