import {
  CustomModalLayout,
  CustomModalLayoutProps,
  ModalProps,
  Text,
  TableActionCellSecondaryAction,
} from '@wix/design-system';
import React from 'react';
import { observer } from 'mobx-react-lite';
import { ModalWrapper } from '../CollectionModal';
import { ConditionalModalState } from '@wix/bex-core';

export interface CustomActionModalProps
  extends Partial<CustomModalLayoutProps> {
  state: ConditionalModalState<unknown>;
  onAfterClose?: ModalProps['onAfterClose'];
  actionProps?: Partial<TableActionCellSecondaryAction>;
  /** z-index of the modal overlay, forwarded to the underlying WDS `Modal`. */
  zIndex?: ModalProps['zIndex'];
}

function _CustomActionModal({
  state,
  content,
  onAfterClose,
  primaryButtonOnClick,
  secondaryButtonOnClick,
  onCloseButtonClick,
  zIndex,
  ...rest
}: CustomActionModalProps) {
  const { modal } = state;

  return (
    <ModalWrapper
      state={modal}
      zIndex={zIndex}
      onAfterClose={() => {
        state.afterClose();
        onAfterClose?.();
      }}
    >
      <CustomModalLayout
        dataHook="collection-action-modal"
        {...rest}
        onCloseButtonClick={(e) => {
          modal.close();
          onCloseButtonClick?.(e);
        }}
        primaryButtonOnClick={() => {
          modal.confirm();
          primaryButtonOnClick?.();
        }}
        secondaryButtonOnClick={
          rest.secondaryButtonText
            ? () => {
                modal.decline();
                secondaryButtonOnClick?.();
              }
            : undefined
        }
        content={typeof content === 'string' ? <Text>{content}</Text> : content}
      />
    </ModalWrapper>
  );
}

export const CustomActionModal = observer(_CustomActionModal);
