"use client";
import React, {
  useState,
  useEffect,
  useRef,
  SetStateAction,
  Dispatch,
} from "react";
import { Button } from "@/components/ui/button";
import { usePathname } from "next/navigation";
import LoadingSpinner from "./LoadingSpinner";

interface popUpTypes {
  title: string;
  message: string;
  message2?: string;
  isOpen: boolean;
  onClose: () => void;
  handleDeactivateAccount?: ({ field }: any) => Promise<void>;
  setDeactivate?: Dispatch<SetStateAction<string>>;
  loading?: boolean;
}

export default function Popup({
  title,
  isOpen = false,
  onClose,
  message,
  message2,
  handleDeactivateAccount,
  setDeactivate,
  loading,
}: popUpTypes) {
  const [animationState, setAnimationState] = useState<
    "closed" | "entering" | "entered" | "exiting"
  >("closed");
  const popupRef = useRef<null | HTMLDivElement>(null);
  const pathname = usePathname();
  const isAdminRoute = pathname.includes("/admin");

  useEffect(() => {
    if (isOpen && animationState === "closed") {
      if (isAdminRoute) {
        // For admin routes - use animation
        setAnimationState("entering");
        setTimeout(() => setAnimationState("entered"), 300);
      } else {
        // For user routes - no animation, just show
        setAnimationState("entered");
      }
    } else if (
      !isOpen &&
      (animationState === "entering" || animationState === "entered")
    ) {
      if (isAdminRoute) {
        // For admin routes - use exit animation
        setAnimationState("exiting");
        setTimeout(() => setAnimationState("closed"), 300);
      } else {
        // For user routes - no animation, just close
        setAnimationState("closed");
      }
    }
  }, [isOpen, animationState, isAdminRoute]);

  // Handle click outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (
        popupRef.current &&
        !popupRef.current.contains(event.target as Node) &&
        animationState === "entered"
      ) {
        onClose();
      }
    }

    // Add event listener only when popup is open
    if (animationState === "entered" || animationState === "entering") {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [onClose, animationState]);

  if (animationState === "closed") return null;

  const getAnimationClass = () => {
    if (!isAdminRoute) {
      // No animations for user routes
      return "translate-x-0 opacity-100";
    }

    switch (animationState) {
      case "entering":
        return "translate-x-0 opacity-100 animate-slide-in";
      case "entered":
        return "translate-x-0 opacity-100";
      case "exiting":
        return "-translate-x-full opacity-0 animate-slide-out";
      default:
        return "-translate-x-full opacity-0";
    }
  };

  const handleProceed = async () => {
    setDeactivate?.("1");
    await handleDeactivateAccount?.({ field: "deactive_account" });
    onClose();
  };

  return (
    <div className="fixed inset-0 flex items-center justify-center p-4 z-50 bg-black/50 transition-opacity duration-300 ease-in-out">
      <div
        ref={popupRef}
        className={`bg-white w-full max-w-md rounded-md shadow-md mx-auto transition-all duration-300 ease-in-out ${getAnimationClass()}`}
      >
        <div className="p-6 space-y-4">
          <h1 className="text-[13px] font-semibold text-black border-b border-gray-200 pb-4">
            {title}
          </h1>
          <p className="text-black text-base text-[12px] leading-relaxed">
            {message}
          </p>

          {pathname.includes("/user/settings") && (
            <p className="text-black text-base text-[12px] leading-relaxed mt-3">
              {message2}
            </p>
          )}
        </div>

        <div className="px-6 py-4 w-full flex justify-end">
          <div className="flex flex-col sm:flex-row gap-4">
            <Button
              onClick={() => handleProceed()}
              className={`w-full sm:w-auto ${pathname.includes("/admin") ? "bg-[#16166C]" : "bg-[#EF2424]"} cursor-pointer text-white text-[12px] px-4 py-3
                        rounded-full transition-colors duration-200`}
            >
              {loading ? <LoadingSpinner /> : "Proceed"}
            </Button>
            <Button
              variant="outline"
              className={`w-full sm:w-auto text-[12px]
                        px-4 py-3 rounded-full transition-colors duration-200 ${pathname.includes("/admin") ? "text-[#16166C] border-[#16166C]" : "text-[#EF2424] border-[#EF2424]"}`}
              onClick={onClose}
            >
              Cancel
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
