"use client";

import { useEffect, useState } from "react";
import clsx from "clsx";

import { closeModalWithCleanup } from "@/shared/utils/modal";

import { Button, Icon, IconName, Modal, ModalProps } from "..";

import styles from "./ModalSheet.module.scss";

interface ModalSheetProps extends Omit<ModalProps, "isCloseButtonVisible"> {
  showCloseButton?: boolean;
  variant?: "white" | "gray";
  disableBackdropClose?: boolean;
}

export default function ModalSheet({
  open,
  onClose,
  children,
  className,
  modalClassName,
  showCloseButton = true,
  variant = "white",
  disableBackdropClose = false,
  ref,
}: ModalSheetProps) {
  const [isOpen, setIsOpen] = useState(open);

  useEffect(() => {
    const timeout = setTimeout(() => {
      setIsOpen(open);
    }, 300);

    return () => clearTimeout(timeout);
  }, [open]);

  return (
    <Modal
      open={open || isOpen}
      onClose={
        disableBackdropClose
          ? () => {
              /* Backdrop close disabled */
            }
          : onClose
      }
      className={clsx(className, styles.overlay, {
        [styles.closed]: !open && isOpen,
      })}
      modalClassName={clsx(styles.sheet, modalClassName, {
        [styles.closed]: !open && isOpen,
        [styles.gray]: variant === "gray",
      })}
      isCloseButtonVisible={false}
      ref={ref}
    >
      {showCloseButton && (
        <Button
          className={styles.crossButton}
          onClick={() => closeModalWithCleanup(onClose)}
        >
          <Icon
            name={IconName.Cross}
            size={{
              height: 12,
              width: 12,
            }}
            color={variant === "gray" ? "#FFFFFF" : "#585E69"}
          />
        </Button>
      )}
      {children}
    </Modal>
  );
}
