import { Link } from "@inertiajs/react";
import React from "react";
import { motion } from "framer-motion";
import { ChevronDown } from "lucide-react";
import { MENU_ICON_MAP } from "../configs/menuConfig";

function NavLink({
  active = false,
  icone = "",
  label,
  arrow = false,
  children,
  to,
  isOpen = false,
  onToggle,
}) {
  const isGroup = !!children;

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

  return (
    <>
      {isGroup ? (
        <li className="side-bar-nav-item rounded-md mb-1.5">
          <button
            type="button"
            onClick={onToggle}
            className="js-more-trigger w-full flex items-center justify-between px-2 py-1.5 text-[12px] font-semibold text-slate-500 uppercase tracking-wider hover:text-slate-700 transition-colors cursor-pointer"
          >
            <span className="truncate">{label}</span>

            <motion.div
              className="js-more-arrow text-[11px] flex items-center justify-center"
              animate={{ rotate: isOpen ? 0 : -90 }}
              transition={{ duration: 0.18 }}
            >
              <ChevronDown className="w-[14px] h-[14px]" />
            </motion.div>
          </button>
          <motion.div
            initial={false}
            animate={isOpen ? "open" : "closed"}
            variants={{
              open: { height: "auto", opacity: 1 },
              closed: { height: 0, opacity: 0 },
            }}
            style={{ overflow: "hidden" }}
          >
            <ul className="hideble-ul text-skin-muted space-y-1 py-1 pl-2 ml-0.5">
              {children}
            </ul>
          </motion.div>
        </li>
      ) : (
        <Link className="navlink" href={route(to)}>
          <li className="side-bar-nav-item rounded-md mb-1.5">
            <div
              className={`js-more-trigger flex items-center gap-3 cursor-pointer rounded-lg px-3 py-2 text-sm font-medium transition-colors ${active
                ? "bg-blue-50 text-blue-700 border-l-2 border-blue-600 -ml-0.5 pl-[14px]"
                : "text-slate-500 hover:bg-slate-50 hover:text-slate-700"
                }`}
            >
              {icone &&
                (() => {
                  const IconComponent =
                    typeof icone === "string" ? getLucideIcon(icone) : icone;

                  if (!IconComponent) return null;

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

              <span className="font-medium text-sm truncate">{label}</span>
            </div>
          </li>
        </Link>
      )}
    </>
  );
}

export default NavLink;
