import React, { useState, useEffect } from "react";
import { Modal } from "../Modal";
import "./BottomSheet.styles.scss";

export const BottomSheet = ({
  open,
  onClose,
  title,
  children,
  footerOptions,
  maxHeight = "calc(100vh - 64px)",
  withExpandIcon = false,
  ...props
}) => {
  const [isExpanded, setIsExpanded] = useState(false);

  const handleExpandClick = () => {
    setIsExpanded(!isExpanded);
    if (props?.onExpand) {
      props?.onExpand(!isExpanded);
    }
  };

  const [contentHeight, setContentHeight] = useState("auto");

  useEffect(() => {
    if (open) {
      setContentHeight("auto");
      const timeout = setTimeout(() => {
        const height =
          document.querySelector(".ia_modalBody")?.scrollHeight + 105;
        const cappedHeight = height > maxHeight ? maxHeight : `${height}px`;
        setContentHeight(cappedHeight);
      }, 0);
      return () => clearTimeout(timeout);
    } else {
      setContentHeight("auto");
    }
  }, [open, children, maxHeight]);

  const hasFooter = footerOptions && Object.keys(footerOptions)?.length > 0;

  return (
    <Modal
      title={title}
      open={open}
      onClose={onClose}
      className={`bottom-sheet ${isExpanded ? "expanded" : ""} ${
        hasFooter ? "with-footer" : ""
      }`}
      isBottomSheet={true}
      isExpanded={isExpanded}
      onExpand={handleExpandClick}
      footerOptions={footerOptions}
      height={!withExpandIcon && contentHeight}
      maxHeight={!withExpandIcon && maxHeight}
      withExpandIcon={withExpandIcon}
      {...props}
    >
      {children}
    </Modal>
  );
};
