import * as Ariakit from '@ariakit/react';
import { useDrawer } from '@websolutespa/bom-mixer-hooks';
import { ReactElement } from 'react';
import { useVariants } from '../../variants';
import { DrawerBackdrop } from './drawer-backdrop';
import { DrawerDialog, DrawerDialogProps } from './drawer-dialog';
import { DrawerProvider } from './drawer.context';
import { drawerVariants } from './drawer.variants';

export type DrawerProps = DrawerDialogProps & {
  name: string;
  visible?: boolean;
  onClose?: () => void;
  disclosure?: ReactElement;
};

export const Drawer = ({
  name,
  visible: outerVisible,
  onClose: outerOnClose,
  variant = 'default',
  variants,
  children,
  disclosure,
  ...props
}: DrawerProps) => {
  const [drawer, openDrawer, closeDrawer] = useDrawer();

  const onClose = () => {
    if (outerOnClose) {
      outerOnClose();
    }
    if (drawer === name) {
      closeDrawer();
    }
  };

  const open = typeof outerVisible === 'undefined' ?
    drawer === name :
    outerVisible;

  const globalVariants = useVariants('drawer', drawerVariants);
  variants = variants || globalVariants;
  return (
    <DrawerProvider value={{
      name,
      variant,
      variants,
    }}>
      <Ariakit.DialogProvider
        open={open}
      >
        {disclosure && (
          <Ariakit.DialogDisclosure render={disclosure}></Ariakit.DialogDisclosure>
        )}
        <DrawerDialog
          backdrop={<DrawerBackdrop />}
          onClose={() => onClose()}
          variant={variant}
          variants={variants}
          {...props}
          data-lenis-prevent
        >
          {children}
        </DrawerDialog>
      </Ariakit.DialogProvider>
    </DrawerProvider>
  );
};
