import { useState } from "react";
import { useTranslation } from "react-i18next";
import { MdExpandLess, MdExpandMore } from "react-icons/md";
import { Link, useNavigate } from "react-router-dom";

export const MenuItem = ({ item, location, index }: any) => {
  const isActive = location.pathname.split("/")[1] === item.path?.slice(1);
  // console.log(location.pathname.split("/")[1]);

  const [openDropdown, setOpenDropdown] = useState<number | null>(null);

  const handleDropdown = (index: number) => {
    setOpenDropdown((prev) => (prev === index ? null : index));
  };

  const isDropdownOpen = openDropdown === index;
  const [t] = useTranslation();
  const navigate = useNavigate();

  return (
    <>
      <div
        className={`link ${isActive ? "active" : ""} ${item?.children && "DropDownLink"} `}
        onClick={() => navigate(item.path || "/")}
      >
        <i>{item.icon}</i>
        <Link to={item.path || "/"}>{t(item.text)}</Link>
        {item?.children && (
          <>
            {isDropdownOpen ? (
              <div
                className="DropDownIcon"
                onClick={() => handleDropdown(index)}
              >
                <MdExpandLess />
              </div>
            ) : (
              <div
                className="DropDownIcon"
                onClick={() => handleDropdown(index)}
              >
                <MdExpandMore />
              </div>
            )}
          </>
        )}
      </div>

      {item?.children && isDropdownOpen && (
        <div className="sub-menu">
          {item.children.map((childItem: any, index: any) => (
            <MenuItem
              key={index}
              item={childItem}
              location={location}
              index={index}
            />
          ))}
        </div>
      )}
    </>
  );
};
