"use client";

import React, { useEffect } from "react";

import styles from "@/components/administrator/MiniWondow/miniwindow.module.css";
import { AnimatePresence, motion } from "framer-motion";
import { useDispatch, useSelector } from "react-redux";
import {
  hideMiniWindowOnIndex,
  selectMiniWindow,
} from "@/utils/store/features/ui/miniwindow.slice";

// icons
import { IoClose } from "react-icons/io5";

const MiniWindowComponent = (props) => {
  const dispatch = useDispatch();

  return (
    <>
      <AnimatePresence>
        {props.status && (
          <motion.div
            initial={{ y: 800, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 800, opacity: 0 }}
            transition={{ duration: 0.4 }}
            className={styles.mini_container}
            onClick={(e) => e.stopPropagation()}
            style={{
              height: props.height
                ? props.height
                : `calc(100% - (${props.index + 1} * ${
                    props.space ? props.space : 100
                  }px))`,
            }}>
            <IoClose
              className={styles.close}
              onClick={() => {
                dispatch(hideMiniWindowOnIndex(props.index));
              }}
            />
            <div className={styles.content}>
              {(() => {
                if (!props.component) return <>No Component is Set</>;
                const Component = props.component;
                return <Component {...props} />;
              })()}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

const MiniWindow = () => {
  const dispatch = useDispatch();
  const miniWindow = useSelector(selectMiniWindow);

  // useEffect(() => {
  //   const handleKeyDown = (e) => {
  //     if (e.key === "Escape") {
  //       dispatch(hideMiniWindowOnIndex(miniWindow.length - 1));
  //     }
  //   };

  //   document.addEventListener("keydown", handleKeyDown);
  //   return () => {
  //     document.removeEventListener("keydown", handleKeyDown);
  //   };
  // }, [miniWindow, dispatch]);

  return (
    <>
      <AnimatePresence>
        {miniWindow.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.4 }}
            onClick={(e) => {
              dispatch(hideMiniWindowOnIndex(miniWindow.length - 1));
            }}
            className={styles.container}>
            {miniWindow.map((item, index) => (
              <MiniWindowComponent
                key={index}
                {...item}
                index={index}
              />
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

export default MiniWindow;
