import React, { useState, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import styles from "./DropdownMenu.module.scss";
import { useGetCategoriesQuery } from "../../app/api/categories";
import { CategoryIcon } from "../Icons";
import { ChevronRight, ChevronDown } from "lucide-react"; // Assuming you have access to lucide-react or similar
const NestedCategory = ({
category,
level = 0,
handleCategorySelect,
closeDropdown,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const hasChildren = category.children && category.children.length > 0;
const handleClick = (e) => {
e.stopPropagation();
if (hasChildren) {
setIsExpanded(!isExpanded);
} else {
handleCategorySelect(category);
closeDropdown();
}
};
const handleDirectNavigation = (e) => {
e.stopPropagation();
handleCategorySelect(category);
closeDropdown();
};
return (
{category.name}
{hasChildren && (
)}
{hasChildren && (
)}
{hasChildren && isExpanded && (
{category.children.map((child) => (
))}
)}
);
};
const DropdownMenu = () => {
const { t } = useTranslation();
const navigate = useNavigate();
const dropdownRef = useRef(null);
const {
data: categoriesData,
isLoading,
error,
} = useGetCategoriesQuery("tree");
const categories = categoriesData?.data || [];
const [isOpen, setIsOpen] = useState(false);
const [activeMainCategory, setActiveMainCategory] = useState(null);
useEffect(() => {
if (categories.length > 0) {
const defaultCategory =
categories.find((cat) => cat.name === "Aýallar üçin") || categories[0];
setActiveMainCategory(defaultCategory);
}
}, [categories]);
const handleToggle = () => {
setIsOpen(!isOpen);
};
const handleMouseLeave = () => {
if (categories.length > 0) {
const defaultCategory =
categories.find((cat) => cat.name === "Aýallar üçin") || categories[0];
setActiveMainCategory(defaultCategory);
}
};
const handleCategorySelect = (category) => {
navigate(`/category/${category.id}`, { state: { category } });
setIsOpen(false);
};
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
setIsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
if (isLoading) return Loading...
;
if (error) return Error loading categories
;
return (
{isOpen && (
{categories.map((category) => (
setActiveMainCategory(category)}
onClick={() => handleCategorySelect(category)}
>
{category.name}
))}
{activeMainCategory && (
handleCategorySelect(activeMainCategory)}
className={styles.title}
>
{activeMainCategory.name}
{activeMainCategory.children &&
activeMainCategory.children.length > 0 ? (
activeMainCategory.children.map((subcategory) => (
setIsOpen(false)}
/>
))
) : (
{/* No subcategories available */}
)}
)}
)}
);
};
export default DropdownMenu;