import React from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { Grid, Theme } from '@radix-ui/themes';
import { usePortalContainer } from '@/theme/portal-provider';
import { ClosePanelArrowIcon } from '../icons/close-panel-arrow';
import { Flex } from './flex';
import { Separator } from './separator';
import { IconButton } from './icon-button';

export function Root(props: Dialog.DialogProps): React.ReactNode {
  return <Dialog.Root {...props} />;
}

type ContentProps = Dialog.DialogContentProps & {
  /** Drawer가 붙는 위치, 기본값 right */
  position?: 'left' | 'right' | 'bottom' | 'top';
};

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

export function Content(props: ContentProps): React.ReactElement {
  const { position = 'right', className, children, ...rest } = props;

  const mobileHeaderSize = 48;
  const desktopHeaderSize = 64;
  const separatorSize = 1;
  const { drawerContainerRef } = usePortalContainer();

  return (
    <Dialog.Portal container={drawerContainerRef.current}>
      <Theme>
        <Dialog.Overlay className="DrawerOverlay" />
        <Dialog.Content
          className={`DrawerContent ${position} ${className || ''}`}
          onPointerDownOutside={preventDefault}
          {...rest}
        >
          <Grid
            height="100%"
            overflow="hidden"
            rows={{
              initial: `${mobileHeaderSize}px ${separatorSize}px calc(100% - ${mobileHeaderSize + separatorSize}px)`,
              sm: `${desktopHeaderSize}px ${separatorSize}px calc(100% - ${desktopHeaderSize + separatorSize}px)`,
            }}
          >
            <Flex align="center" px={{ initial: '4', md: '6' }}>
              <Dialog.Close asChild>
                <IconButton color="gray" variant="outline">
                  <ClosePanelArrowIcon />
                </IconButton>
              </Dialog.Close>
            </Flex>
            <Separator orientation="horizontal" size="4" />
            {children}
          </Grid>
        </Dialog.Content>
      </Theme>
    </Dialog.Portal>
  );
}

export function Trigger(props: Dialog.DialogTriggerProps): React.ReactElement {
  return <Dialog.Trigger asChild {...props} />;
}

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