import { forwardRef, useMemo } from 'react';

import type { ContainerRef } from '@cleartrip/ct-design-container';
import {
  ActionButtonAlignment,
  ActionButtonVariant,
  Modal,
  type ActionButtonAlignmentType,
  type ActionButtonVariantsType,
} from '@cleartrip/ct-design-modal';

import type { IDialogProps } from './type';

/**
 * Native implementation of `Dialog`.
 *
 * Migrated 1:1 from aldenui (`core/components/components/Dialog`).
 * The native `Modal` already implements the `actionButtonType` +
 * `actionButtonAlignment` slots, so this wrapper only needs to
 * translate the legacy `overlayCloseIcon` flag set and forward
 * everything else unchanged.
 */
const Dialog = forwardRef<ContainerRef, IDialogProps>(
  (
    {
      children,
      open,
      variant,
      placement,
      blur,
      allowBackdropClose,
      overlayCloseIcon,
      onClose,
      styleConfig,
      size,
      actionButtonType: actionButtonTypeFromProps,
      actionButtonAlignment: actionButtonAlignmentFromProps,
    },
    forwardedRef,
  ) => {
    const { root: customRootStyles = [], modalWrapperStyles = [] } = styleConfig || {};
    const { show = false, isBack = false, showCloseIcon = false, isCenter = false } = overlayCloseIcon || {};

    const actionButtonAlignment = useMemo<ActionButtonAlignmentType>(() => {
      if (actionButtonAlignmentFromProps) return actionButtonAlignmentFromProps;
      if (isBack) return ActionButtonAlignment.LEFT;
      if (isCenter) return ActionButtonAlignment.CENTER;
      return ActionButtonAlignment.RIGHT;
    }, [actionButtonAlignmentFromProps, isBack, isCenter]);

    const actionButtonType = useMemo<ActionButtonVariantsType>(() => {
      if (actionButtonTypeFromProps) return actionButtonTypeFromProps;
      if (isBack) return ActionButtonVariant.BACK;
      if (showCloseIcon) return ActionButtonVariant.CLOSE;
      return ActionButtonVariant.NONE;
    }, [actionButtonTypeFromProps, isBack, showCloseIcon, show]);

    return (
      <Modal
        ref={forwardedRef}
        variant={variant}
        placement={placement}
        allowBackdropClose={allowBackdropClose}
        onClose={onClose}
        blur={blur}
        open={open}
        size={size}
        actionButtonType={actionButtonType}
        actionButtonAlignment={actionButtonAlignment}
        styleConfig={{
          root: customRootStyles,
          modalContentStyles: modalWrapperStyles,
        }}
      >
        {children}
      </Modal>
    );
  },
);

Dialog.displayName = 'Dialog';

export default Dialog;
