import { useEffect, useState, useRef } from "react";
import { ArrowRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { useDrawerStore } from "../../context/zustand-store/appStore";
import { checkIsMobile } from "../../utils/checkIsMobile";
import { panelBgAndTextColors } from "../../data/getColorBasedOnMode";
import Divider from "../Divider/Divider";

type Direction = "top" | "bottom" | "left" | "right" | null;

const Drawer: React.FC = () => {
  const { drawerState, closeDrawer } = useDrawerStore();
  const [shouldRender, setShouldRender] = useState<boolean>(
    !!drawerState.isOpen
  );
  const [animate, setAnimate] = useState<boolean>(false);
  const [mouseDownTarget, setMouseDownTarget] = useState<EventTarget | null>(
    null
  );
  const drawerRef = useRef<HTMLDivElement>(null);

  const rawDirection = drawerState.direction;

  const direction: Direction = checkIsMobile()
    ? "top"
    : rawDirection && ["top", "bottom", "left", "right"].includes(rawDirection)
    ? (rawDirection as Direction)
    : "left";

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === mouseDownTarget && e.target === e.currentTarget) {
      closeDrawer();
    }
  };

  const handleMouseDown = (e: React.MouseEvent) => {
    setMouseDownTarget(e.target);
  };

  useEffect(() => {
    if (drawerState.isOpen) {
      setShouldRender(true);
      requestAnimationFrame(() => {
        setAnimate(true);
      });
    } else {
      setAnimate(false);
      const timer = setTimeout(() => setShouldRender(false), 500);
      return () => clearTimeout(timer);
    }
  }, [drawerState.isOpen]);

  if (!shouldRender) {
    return null;
  }

  const directionClasses: Record<Exclude<Direction, null>, string> = {
    top: "transform -translate-y-full",
    bottom: "transform translate-y-full",
    left: "transform -translate-x-full",
    right: "transform translate-x-full",
  };

  const openClasses: Record<Exclude<Direction, null>, string> = {
    top: "top-0 left-0 right-0 w-full h-full sm:h-1/3 sm:w-auto translate-y-0 top-0",
    bottom:
      "bottom-0 left-0 right-0 w-full h-full sm:h-1/3 sm:w-auto translate-y-0 bottom-0",
    left: "left-0 top-0 bottom-0 h-full sm:w-1/2 md:w-2/4 lg:w-[400px]  translate-x-0",
    right:
      "right-0 top-0 bottom-0 h-full sm:w-1/2 md:w-2/4 lg:w-[400px] translate-x-0",
  };

  const isMobile = checkIsMobile();
  if ((direction === "left" || direction === "right") && isMobile) {
    openClasses.left = "left-0 top-0 bottom-0 w-full h-full translate-x-0";
    openClasses.right = "right-0 top-0 bottom-0 w-full h-full translate-x-0";
  }

  const currentClasses =
    direction && animate && direction in openClasses
      ? openClasses[direction]
      : direction
      ? directionClasses[direction]
      : "";

  return (
    <div
      className={`fixed inset-0 bg-opacity-50 transition-opacity duration-300 
        ${drawerState.isOpen ? "opacity-100" : "opacity-0 pointer-events-none"} 
        flex z-50`}
      onClick={handleBackdropClick}
      onMouseDown={handleMouseDown}
    >
      <div
        ref={drawerRef}
        className={`${panelBgAndTextColors} fixed shadow-lg p-4 transition-transform duration-300 ease-in-out 
          ${currentClasses} ${!animate ? "opacity-0" : "opacity-100 "}`}
        onClick={(e) => e.stopPropagation()}
      >
        {checkIsMobile() ? (
          <div className=" items-center justify-between pb-2">
            <div className="flex items-center justify-between pb-2">
              <button
                onClick={closeDrawer}
                className="text-primary-500 hover:text-blue-600 transition-colors"
              >
                <ArrowRightIcon className="w-6 h-6" />
              </button>
              <h2 className="text-base font-medium text-gray-900 dark:text-white">
                {drawerState?.title}
              </h2>
              <div className="w-5" />
            </div>
            <Divider />
          </div>
        ) : (
          <div className="flex justify-between items-center border-b pb-2 ">
            <h2 className="text-lg ">{drawerState.title}</h2>
            <button
              onClick={closeDrawer}
              className="mr-1 text-primary-500 hover:text-red-700 dark:text-white rounded-full p-0.5 transition-colors cursor-pointer "
            >
              <XMarkIcon className="h-5.5 5-3.5" />
            </button>
          </div>
        )}

        <div className="p-4 overflow-y-auto max-h-[94vh] scrollbar-hidden pb-24">
          {drawerState.content}
        </div>
      </div>
    </div>
  );
};

export default Drawer;
