import * as RadixDialog from '@radix-ui/react-dialog';
import { Cross1Icon } from '@radix-ui/react-icons';
import { Flex, Theme } from '@radix-ui/themes';
import { ToastContainer } from './toast';
import { Heading } from './heading';
import { IconButton } from './icon-button';

type ContentProps = RadixDialog.DialogContentProps & {
  width?: string;
  maxWidth?: string;
  minWidth?: string;
  height?: string;
  maxHeight?: string;
  minHeight?: string;
  title?: string;
  hideCloseButton?: boolean;
  buttons?: React.ReactElement;
};

const preventDefault: RadixDialog.DialogContentProps['onPointerDownOutside'] = (
  e
) => {
  e.preventDefault();
};

function Content(props: ContentProps): React.ReactElement {
  const {
    children,
    style = {},
    width,
    maxWidth,
    minWidth,
    maxHeight,
    height,
    minHeight,
    title,
    buttons,
    hideCloseButton,
    className,
    ...rest
  } = props;

  return (
    <RadixDialog.Portal>
      <Theme asChild>
        <RadixDialog.Overlay className="DialogOverlay">
          <RadixDialog.Content
            className={`DialogContent ${className || ''}`}
            onPointerDownOutside={preventDefault}
            style={{
              width,
              maxWidth,
              minWidth,
              maxHeight,
              height,
              minHeight,
              ...style,
            }}
            {...rest}
          >
            <Flex gap="2" justify="between">
              <RadixDialog.Title asChild>
                {typeof title === 'string' ? (
                  <Heading align="center" mb="2" variant="heading3">
                    {title}
                  </Heading>
                ) : (
                  title
                )}
              </RadixDialog.Title>
              {!hideCloseButton && (
                <RadixDialog.Close asChild className="DialogClose">
                  <IconButton color="gray" variant="ghost">
                    <Cross1Icon />
                  </IconButton>
                </RadixDialog.Close>
              )}
            </Flex>
            {children}
            {buttons ? (
              <Flex gap="3" justify="end" mt="3">
                {buttons}
              </Flex>
            ) : null}
          </RadixDialog.Content>
          <ToastContainer />
        </RadixDialog.Overlay>
      </Theme>
    </RadixDialog.Portal>
  );
}

function Close({
  children,
  ...rest
}: RadixDialog.DialogCloseProps): React.ReactElement {
  return (
    <RadixDialog.Close asChild {...rest}>
      {children}
    </RadixDialog.Close>
  );
}

function Trigger({
  children,
  ...rest
}: RadixDialog.DialogTriggerProps): React.ReactElement {
  return (
    <RadixDialog.Trigger asChild {...rest}>
      {children}
    </RadixDialog.Trigger>
  );
}

export const Dialog = {
  Root: RadixDialog.Root,
  Trigger,
  Content,
  Close,
  Description: RadixDialog.Description,
  Title: RadixDialog.Title,
};
