"use client";

import React from "react";
import { createPortal } from "react-dom";
import { SelectMenuPortalContext } from "./SelectMenuPortal";
import { X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/helpers";
import { useModalKeyboard } from "./useModalKeyboard";
import { lockBodyScroll, unlockBodyScroll } from "./modalStack";
import { modalContentVariants, modalVariants } from "./modalVariants";

interface ModalProps
  extends
    React.HTMLAttributes<HTMLDivElement>,
    VariantProps<typeof modalContentVariants> {
  open?: boolean;
  onClose?: () => void;
  closeOnOutsideClick?: boolean;
  showCloseButton?: boolean;
  title?: string;
  footer?: React.ReactNode;
  position?: "default" | "top" | "bottom";
  size?: "sm" | "md" | "lg" | "xl" | "2xl" | "full" | "small";
  disableFilterModalClass?: boolean;
  compactFilter?: boolean;
}

const Modal = React.forwardRef<HTMLDivElement, ModalProps>(
  (
    {
      className,
      children,
      position,
      size,
      open = false,
      onClose,
      closeOnOutsideClick = true,
      showCloseButton = true,
      title,
      footer,
      disableFilterModalClass = false,
      compactFilter = false,
      ...props
    },
    ref,
  ) => {
    const { t } = useTranslation();
    const titleId = React.useId();
    const [isVisible, setIsVisible] = React.useState(open);
    const [selectMenuHost, setSelectMenuHost] = React.useState<HTMLDivElement | null>(null);
    /*
     * The dialog panel, for the keyboard hook. Separate from the forwarded
     * `ref`, which callers own and which is not always supplied.
     */
    const panelRef = React.useRef<HTMLDivElement | null>(null);
    useModalKeyboard({ open, onClose, containerRef: panelRef });

    React.useEffect(() => {
      setIsVisible(open);
      if (!open) return;

      // Reference-counted: an inner dialog closing must not unlock a page that an
      // outer dialog is still covering (see `modalStack`).
      lockBodyScroll();
      return unlockBodyScroll;
    }, [open]);

    const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
      if (e.target === e.currentTarget && closeOnOutsideClick && onClose) {
        onClose();
      }
    };

    if (!isVisible || typeof document === "undefined") return null;

    // Escape sticky/scrolling ancestors so the dialog overlays the whole page.
    return createPortal(
      <SelectMenuPortalContext.Provider value={selectMenuHost}>
      <div
        className={cn(modalVariants({ position }))}
        /* Click-outside-to-close. jsx-a11y's strict preset reports the
           missing key handler; the keyboard equivalent is Escape, which
           `useModalKeyboard` above binds (along with the focus trap), and
           giving the backdrop a role and a tab stop of its own would put a
           phantom control inside the dialog it is meant to dismiss. */
        onClick={handleBackdropClick}
        aria-modal="true"
        role="dialog"
        aria-labelledby={title ? titleId : undefined}
        {...props}
      >
        <div className="fixed inset-0 bg-[#000000]/80" aria-hidden="true" />
        <div
          ref={(node) => {
            panelRef.current = node;
            if (typeof ref === "function") ref(node);
            else if (ref) ref.current = node;
          }}
          tabIndex={-1}
          className={cn(
            modalContentVariants({ size }),
            !disableFilterModalClass && "filtermodal",
            "max-h-[calc(100vh-100px)]",
            className,
            compactFilter && "compact-filter-dialog",
          )}
        >
          {(title || showCloseButton) && (
            <div className="flex items-center justify-between border-b-2 border-[#727272] laptop:py-4 lg:py-4 py-4 2xl:px-9 px-9">
              {title && (
                <h2 id={titleId} className="font-bold text-primary-5 2xl:text-[32px] lg:text-[24px] text-[22px] extrasmall:text-[16px] xss:text-[20px] xsl:text-[25px] xss1:text-[14px]">
                  {title}
                </h2>
              )}
              {showCloseButton && (
                <button
                  type="button"
                  onClick={onClose}
                  className="ml-auto rtl:ml-0 flex h-8 w-8 items-center justify-center rounded-full hover:bg-gray-100"
                  aria-label={t("COMMON.CLOSE")}
                >
                  <X className="h-6 w-6 text-[#222222]" />
                </button>
              )}
            </div>
          )}
          <div className="flex-1 2xl:px-[40px] lg:px-[30px] px-[30px] mobilescreen:px-[20px] lg:pt-6 pt-[20px] lg:pb-6 pb-[20px] overflow-y-auto bg-white">
            {children}
            {footer && <div className="">{footer}</div>}
          </div>
        </div>
        <div ref={setSelectMenuHost} data-select-menu-host />
      </div>
      </SelectMenuPortalContext.Provider>,
      document.body,
    );
  },
);
Modal.displayName = "Modal";

const ModalHeader = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("flex flex-col space-y-1.5 p-4 pb-0", className)}
    {...props}
  />
));
ModalHeader.displayName = "ModalHeader";

const ModalTitle = React.forwardRef<
  HTMLHeadingElement,
  React.HTMLAttributes<HTMLHeadingElement>
>(({ className, children, ...props }, ref) => (
  /* `children` is named rather than left in `...props`: a heading with no
     content is announced as an empty landmark, and spreading hid from both
     the reader and the linter whether anything ever fills it. Every call site
     passes a title. */
  <h2
    ref={ref}
    className={cn("text-xl font-semibold text-[#170a51]", className)}
    {...props}
  >
    {children}
  </h2>
));
ModalTitle.displayName = "ModalTitle";

const ModalBody = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("flex-1 p-4 overflow-y-auto scrollbar-hide", className)}
    {...props}
  />
));
ModalBody.displayName = "ModalBody";

const ModalFooter = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("flex items-center justify-end gap-2 p-4 pt-0", className)}
    {...props}
  />
));
ModalFooter.displayName = "ModalFooter";

export { Modal, ModalHeader, ModalTitle, ModalBody, ModalFooter };
