import { Link } from "@inertiajs/react";
import React, { useState, useRef, useEffect } from "react";
import IconNavChild from "./IconNavChild";
import { MENU_ICON_MAP } from "../configs/menuConfig";

function IconNavLink({
  active = false,
  icone = "",
  label,
  children,
  to,
  menuId,
  parentId
}) {
  const [showPopup, setShowPopup] = useState(false);
  const [popupPosition, setPopupPosition] = useState({ top: 0, left: 0 });
  const iconRef = useRef(null);
  const popupRef = useRef(null);

  const getLucideIcon = (name = "") => MENU_ICON_MAP[name] || null;

  // Calculate popup position on hover
  useEffect(() => {
    if (showPopup && iconRef.current && popupRef.current) {
      const iconRect = iconRef.current.getBoundingClientRect();
      const popupWidth = 220; // Fixed popup width
      const popupHeight = popupRef.current.offsetHeight;

      // Position popup to the right of the icon
      const left = iconRect.right + 10;
      const top = iconRect.top;

      // Check if popup goes off screen
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;

      let finalLeft = left;
      let finalTop = top;

      // If popup goes off right edge, show on left side
      if (left + popupWidth > windowWidth) {
        finalLeft = iconRect.left - popupWidth - 10;
      }

      // If popup goes off bottom, adjust top
      if (top + popupHeight > windowHeight) {
        finalTop = windowHeight - popupHeight - 10;
      }

      // Ensure popup doesn't go off top
      if (finalTop < 10) {
        finalTop = 10;
      }

      setPopupPosition({ top: finalTop, left: finalLeft });
    }
  }, [showPopup, children]);

  // Handle mouse enter
  const handleMouseEnter = () => {
    if (children) {
      setShowPopup(true);
    }
  };

  // Handle mouse leave with delay to allow moving to popup
  const handleMouseLeave = () => {
    setTimeout(() => {
      if (!popupRef.current || !popupRef.current.matches(':hover')) {
        setShowPopup(false);
      }
    }, 150);
  };

  // Close popup when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        showPopup &&
        popupRef.current &&
        iconRef.current &&
        !popupRef.current.contains(event.target) &&
        !iconRef.current.contains(event.target)
      ) {
        setShowPopup(false);
      }
    };

    if (showPopup) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showPopup]);

  // Single menu item (no children)
  if (!children) {
    const renderIcon = () => {
      if (!icone) return null;

      const IconComponent =
        typeof icone === "string" ? getLucideIcon(icone) : icone;

      if (!IconComponent) return null;

      return (
        <IconComponent
          className={`w-[20px] h-[20px] ${
            active ? "text-skin-hover" : "text-slate-500"
          }`}
        />
      );
    };

    return (
      <li className="side-bar-nav-item rounded-md">
        <Link
          href={route(to)}
          className="navlink"
          title={label}
        >
          <div
            className={`js-more-trigger font-medium flex items-center ${parentId ? 'justify-start gap-3' : 'justify-center'} cursor-pointer hover:text-skin-hover hover:bg-skin-nav-item-hover transition-colors rounded-md p-3 ${active ? "nav-active font-semibold bg-skin-nav-item-hover" : ""
              }`}
          >
            {renderIcon()}
            {parentId && <span className="text-sm">{label}</span>}
          </div>
        </Link>
      </li>
    );
  }

  // Menu item with children (show popup on hover)
  return (
    <>
      {(() => {
        const renderIcon = () => {
          if (!icone) return null;

          const IconComponent =
            typeof icone === "string" ? getLucideIcon(icone) : icone;

          if (!IconComponent) return null;

          return (
            <IconComponent
              className={`w-[20px] h-[20px] ${
                active ? "text-skin-hover" : "text-slate-500"
              }`}
            />
          );
        };

        return null;
      })()}
      <li
        className="side-bar-nav-item rounded-md relative"
        ref={iconRef}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      >
        <div
          className={`js-more-trigger font-medium flex items-center ${parentId ? 'justify-start gap-3' : 'justify-center'} cursor-pointer hover:text-skin-hover hover:bg-skin-nav-item-hover transition-colors rounded-md p-3 ${active ? "nav-active font-semibold bg-skin-nav-item-hover" : ""
            }`}
          title={label}
        >
          {(() => {
            if (!icone) return null;

            const IconComponent =
              typeof icone === "string" ? getLucideIcon(icone) : icone;

            if (!IconComponent) return null;

            return (
              <IconComponent
                className={`w-[20px] h-[20px] ${
                  active ? "text-skin-hover" : "text-slate-500"
                }`}
              />
            );
          })()}
          {parentId && <span className="text-sm">{label}</span>}
        </div>
      </li>

      {/* Hover Popup */}
      {showPopup && (
        <div
          ref={popupRef}
          className="fixed z-[60] bg-white border border-gray-200 rounded-lg shadow-lg py-2 min-w-[200px] max-w-[250px]"
          style={{
            top: `${popupPosition.top}px`,
            left: `${popupPosition.left}px`,
          }}
          onMouseEnter={() => setShowPopup(true)}
          onMouseLeave={handleMouseLeave}
        >
          {/* Popup Header */}
          <div className="px-4 py-2 border-b border-gray-200">
            <h3 className="font-semibold text-sm text-gray-800">{label}</h3>
          </div>

          {/* Popup Children */}
          <ul className="py-2">
            {children}
          </ul>
        </div>
      )}
    </>
  );
}

export default IconNavLink;
