"use client";

import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useRouter } from "next/navigation";
import { Loader2 } from "lucide-react";
import { PRIMARY_COLOR } from "@/lib/common";

export interface DropdownOption {
  label: string;
  path: string;
}

interface DropdownButtonProps {
  icon?: React.ReactNode;
  options: DropdownOption[];
  buttonLabel?: string;
  className?: string;
}

export default function DropdownButton({
  icon,
  options,
  buttonLabel,
  className,
}: DropdownButtonProps) {
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const router = useRouter();
  const containerRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const [menuPosition, setMenuPosition] = useState<{ top: number; right: number } | null>(null);
  const portalTarget = typeof document !== "undefined" ? document.body : null;

  const updateMenuPosition = () => {
    if (!buttonRef.current) return;
    const rect = buttonRef.current.getBoundingClientRect();
    setMenuPosition({
      top: rect.bottom + window.scrollY,
      right: window.innerWidth - rect.right - window.scrollX,
    });
  };

  useEffect(() => {
    if (!open) return;

    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node;
      if (
        containerRef.current?.contains(target) ||
        menuRef.current?.contains(target)
      ) {
        return;
      }
      setOpen(false);
    };

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setOpen(false);
      }
    };

    const handleScrollOrResize = () => {
      updateMenuPosition();
    };

    updateMenuPosition();

    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("keydown", handleKeyDown);
    window.addEventListener("resize", handleScrollOrResize, true);
    window.addEventListener("scroll", handleScrollOrResize, true);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("resize", handleScrollOrResize, true);
      window.removeEventListener("scroll", handleScrollOrResize, true);
    };
  }, [open]);

  const handleSelect = (path: string) => {
    setOpen(false);
    setLoading(true);
    setTimeout(() => {
      router.push(path);
    }, 200);
  };

  return (
    <div ref={containerRef} className="relative inline-block text-left">
      {/* Main Button */}
      <button
        ref={buttonRef}
        onClick={() => {
          if (loading) return;
          setOpen((prev) => {
            const next = !prev;
            if (next) {
              updateMenuPosition();
            }
            return next;
          });
        }}
        disabled={loading}
        className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg font-medium text-sm border transition-all duration-300 justify-center ${
          loading
            ? "bg-gray-200 text-gray-500 border-gray-200 cursor-not-allowed"
            : "bg-white text-gray-700 border-gray-300 shadow-sm hover:shadow-md active:scale-95"
        } ${className || ""}`}
        style={!loading ? {
          backgroundColor: "white",
        } : {}}
        onMouseEnter={(e) => {
          if (!loading) {
            e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
            e.currentTarget.style.color = "white";
          }
        }}
        onMouseLeave={(e) => {
          if (!loading) {
            e.currentTarget.style.backgroundColor = "white";
            e.currentTarget.style.color = "";
          }
        }}
      >
        {loading ? (
          <>
            <Loader2 className="w-4 h-4 animate-spin" />
            Loading...
          </>
        ) : (
          <>
            {icon}
            {buttonLabel && <span>{buttonLabel}</span>}

          </>
        )}
      </button>

      {open && menuPosition && portalTarget
        ? createPortal(
            <div
              ref={menuRef}
              className="z-50 mt-2 w-48 rounded-lg border border-gray-200 bg-white shadow-lg"
              style={{
                position: "fixed",
                top: menuPosition.top,
                right: menuPosition.right,
              }}
            >
              {options.map((option) => (
                <button
                  key={option.path}
                  onClick={() => handleSelect(option.path)}
                  className="block w-full px-4 py-2 text-left text-sm text-gray-700 transition-colors duration-200"
                  style={{ color: "rgb(55, 65, 81)" }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
                    e.currentTarget.style.color = "white";
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = "";
                    e.currentTarget.style.color = "";
                  }}
                >
                  {option.label}
                </button>
              ))}
            </div>,
            portalTarget
          )
        : null}
    </div>
  );
}
