import React, { useEffect, useRef } from "react";
import "./modal-styles.scss";
import { ModalProps } from "@app/models/components";
import Button from "../button/Button";
import Card from "../card/Card";
import CardHeader from "../card-header/CardHeader";
import CardContent from "../card-content/CardContent";
import CardSection from "../card-section/CardSection";

const Modal: React.FC<ModalProps> = ({
  isOpen,
  onClose,
  title = "",
  modalActions,
  children,
  maxWidth,
}) => {
  const contentRef = useRef<HTMLDivElement>(null);

  const handleScroll = () => {
    if (contentRef.current) {
      const { scrollHeight, scrollTop, clientHeight } = contentRef.current;
      const isEnd = scrollHeight - scrollTop <= clientHeight;

      if (isEnd) {
        contentRef.current.classList.remove("show-border");
      } else {
        contentRef.current.classList.add("show-border");
      }
    }
  };

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    }

    return () => {
      document.body.style.overflow = "auto";
    };
  }, [isOpen]);
  if (!isOpen) return null;
  return (
    <>
      {title && children && (
        <div className="modal-overlay" onClick={onClose}>
          <Card
            elevation={false}
            id="modal-content"
            onClick={(e) => e.stopPropagation()}
            style={{ maxWidth }}
          >
            {title && (
              <CardHeader padding="md" title={title} onClose={onClose} />
            )}
            <div
              ref={contentRef}
              onScroll={handleScroll}
              className="modal-content-container"
            >
              <CardContent padding="md">
                <CardSection padding="md">{children}</CardSection>
              </CardContent>
            </div>
            {!!modalActions?.length && (
              <div className="modal-actionsWrapper">
                {modalActions.map((buttonProps) => (
                  <Button {...buttonProps} />
                ))}
              </div>
            )}{" "}
          </Card>
        </div>
      )}
    </>
  );
};

export default Modal;
