import * as Ariakit from '@ariakit/react';
import { ComponentPropsWithoutRef, forwardRef, useContext } from 'react';
import { Role } from '../role/role';
import { ModalDialogContext } from './modal-dialog.context';

export interface ModalTriggerProps extends ComponentPropsWithoutRef<'button'> {
  asChild?: boolean;
}

export const ModalTrigger = forwardRef<HTMLButtonElement, ModalTriggerProps>(
  function ModalTrigger({ asChild, ...props }, ref) {
    const { store } = useContext(ModalDialogContext)!;
    const open = Ariakit.useStoreState(store, 'open');
    return (
      <Ariakit.DialogDisclosure
        {...props}
        ref={ref}
        store={store}
        data-state={open ? 'open' : 'closed'}
        render={asChild ? <Role /> : undefined}
      />
    );
  }
);
