import {
  Dialog as ArkDialog,
  DialogDescriptionProps,
  DialogTitleProps,
} from '@ark-ui/react';
import { PropsWithChildren } from 'react';
import { twx } from '../utils';

interface DialogProps {
  open: boolean;
  className?: string;
  onRequestClose?: () => void;
  closeOnInteractOutside?: boolean;
  closeButton?: boolean;
}

export const Dialog = ({
  open,
  className,
  children,
  onRequestClose,
  closeOnInteractOutside = true,
  closeButton = true,
}: PropsWithChildren<DialogProps>) => {
  return (
    <ArkDialog.Root
      lazyMount
      open={open}
      onPointerDownOutside={() => {
        if (closeOnInteractOutside) {
          onRequestClose?.();
        }
      }}
    >
      {/* <Portal> */}
      <ArkDialog.Backdrop className="data-[state=closed]:animate-dialog-backdrop-out data-[state=open]:animate-dialog-backdrop-in fixed inset-0 z-90 bg-black/60 backdrop-blur-sm" />
      <ArkDialog.Positioner className="fixed left-0 top-0 z-90 h-100vh w-100vw flex items-center justify-center p-4">
        <ArkDialog.Content
          className={twx([
            'relative data-[state=closed]:animate-dialog-out data-[state=open]:animate-dialog-in',
            className,
          ])}
        >
          {closeButton && (
            <ArkDialog.CloseTrigger
              asChild
              onClick={() => {
                onRequestClose?.();
              }}
            >
              <div className="absolute right-2 top-2 h-9 w-9 cursor-pointer rounded-lg p-2.5 active:backdrop-brightness-80 hover:backdrop-brightness-90 dark:active:backdrop-brightness-120 dark:hover:backdrop-brightness-110">
                <div className="i-mdi-close z-10 h-full w-full text-black/80 dark:text-white/80" />
              </div>
            </ArkDialog.CloseTrigger>
          )}
          {children}
        </ArkDialog.Content>
      </ArkDialog.Positioner>
      {/* </Portal> */}
    </ArkDialog.Root>
  );
};

Dialog.Title = function DialogTitle({
  className,
  ...rest
}: PropsWithChildren<DialogTitleProps>) {
  return (
    <ArkDialog.Title
      className={twx([
        'text-2xl font-bold text-black/70 dark:text-white/70',
        className,
      ])}
      {...rest}
    />
  );
};

Dialog.Description = function DialogDescription({
  className,
  ...rest
}: PropsWithChildren<DialogDescriptionProps>) {
  return (
    <ArkDialog.Description
      className={twx(['text-black/70 text-sm', className])}
      {...rest}
    />
  );
};
