import React from 'react';
import { useOverlayTrigger } from 'react-aria';
import { useOverlayTriggerState } from 'react-stately';
import { DOMAttributes, FocusableElement } from '@react-types/shared';
import clsx from 'clsx';

import { Modal } from './Modal';
import { ModalOpeningButton } from './ModalOpeningButton';

export function ModalTrigger({
  label,
  labelClasses,
  showLabel,
  containerClasses,
  icon,
  isDisabled,
  children,
  scope,
  ...props
}: {
  label: string;
  labelClasses?: string;
  containerClasses?: string;
  showLabel?: boolean;
  icon?: React.ReactNode;
  isDisabled?: boolean;
  children: (onClose: () => void, titleProps: DOMAttributes<FocusableElement>) => React.ReactElement; // Child needs to be a functions which generates the 'content' so we can pass the onClose function and title aria props
  scope: 'squiz-gb-scope' | 'squiz-cb-scope' | 'squiz-rb-scope';
}) {
  const state = useOverlayTriggerState(props);
  const { triggerProps, overlayProps } = useOverlayTrigger({ type: 'dialog' }, state);

  let ariaAttr: React.AriaAttributes = {};
  if (!showLabel) {
    ariaAttr = { ...ariaAttr, 'aria-label': label };
  }

  return (
    <div className={scope}>
      <ModalOpeningButton
        type="button"
        title={label}
        {...triggerProps}
        {...ariaAttr}
        isDisabled={isDisabled}
        className={clsx(
          `${
            containerClasses ||
            'flex p-1 px-1.5 rounded mr-auto text-blue-300 hover:bg-blue-100 focus:bg-blue-100 focus:outline-none'
          }`,
          isDisabled && 'hover:bg-transparent cursor-not-allowed text-gray-600',
        )}
      >
        {icon}
        {showLabel && <span className={`${labelClasses || 'ml-1 text-sm font-semibold leading-4'}`}>{label}</span>}
      </ModalOpeningButton>
      {state.isOpen && (
        <Modal isDismissable state={state} overlayProps={overlayProps} scope={scope}>
          {(titleProps) => children(state.close, titleProps)}
        </Modal>
      )}
    </div>
  );
}
