import { useEffect, useRef } from "react";
import type { ReactNode } from "react";
import { AnimatePresence, motion } from "motion/react";

import SectionSurface from "@components/surface/SectionSurface";
import { useLift } from "@components/lift";
import classes from "./Modal.module.css";
import { clsx, type ClassValue } from "clsx";

type Props = {
  open: boolean;
  children: ReactNode;
  onClose: () => void;
  liftIds?: string[];
  title?: ReactNode;
  className?: ClassValue;
};

export default function Modal({ open, children, onClose, liftIds, title, className }: Props) {
  const { setLiftedIds, registerModal, beginModalClose, endModalClose } = useLift();
  const prevLiftIdsRef = useRef<string>("");

  useEffect(() => {
    if (open) {
      registerModal();
      return () => {
        beginModalClose();
      };
    }
  }, [open, registerModal, beginModalClose]);

  useEffect(() => {
    const key = liftIds?.join(",") ?? "";

    if (open && key) {
      if (key !== prevLiftIdsRef.current) {
        prevLiftIdsRef.current = key;
        setLiftedIds(liftIds!);
      }
    }

    if (!open && prevLiftIdsRef.current) {
      prevLiftIdsRef.current = "";
      setLiftedIds([]);
    }
  }, [open, liftIds, setLiftedIds]);

  useEffect(() => {
    return () => {
      if (prevLiftIdsRef.current) {
        setLiftedIds([]);
      }
    };
  }, [setLiftedIds]);

  return (
    <AnimatePresence onExitComplete={endModalClose}>
      {open && (
        <>
          <motion.div
            className={classes.overlay}
            initial={{ backdropFilter: "blur(0px)" }}
            animate={{ backdropFilter: "blur(8px)" }}
            exit={{ backdropFilter: "blur(0px)" }}
            transition={{ duration: 0.2 }}
            onClick={onClose}
          />
          <motion.div
            className={classes.modalContainer}
            initial={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            onClick={onClose}
          >
            {/* oxlint-disable-next-line jsx_a11y/no-static-element-interactions*/}
            <div
              className={classes.modalInner}
              // oxlint-disable-next-line jsx_a11y/click-events-have-key-events
              onClick={(e) => e.stopPropagation()}
            >
              {title && <div className={classes.title}>{title}</div>}
              <SectionSurface
                className={clsx(classes.modal, className)}
                exit={{ scale: 0 }}
                transition={{ duration: 0.2, type: "spring" }}
              >
                {children}
              </SectionSurface>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
