import { useAuth } from "@web/src/providers/auth-provider";
import { Menu } from "antd";
import { useMemo } from "react";
import { useNavigate, useLocation } from "react-router-dom";

export const NavigationMenu = () => {
	const navigate = useNavigate();
	const { isAuthenticated } = useAuth();
	const { pathname } = useLocation();

	const menuItems = useMemo(() => {
		const baseItems = [
			{ key: "home", path: "/", label: "首页" },
			{ key: "path", path: "/path", label: "全部思维导图" },
			{ key: "courses", path: "/courses", label: "所有课程" },
		];

		if (!isAuthenticated) {
			return baseItems;
		} else {
			return [
				...baseItems,
				{ key: "my-duty", path: "/my-duty", label: "我创建的课程" },
				{ key: "my-learning", path: "/my-learning", label: "我学习的课程" },
				{ key: "my-duty-path", path: "/my-duty-path", label: "我创建的思维导图" },
				{ key: "my-path", path: "/my-path", label: "我学习的思维导图" },
			];
		}
	}, [isAuthenticated]);

	const selectedKey = useMemo(() => {
		const normalizePath = (path: string): string => path.replace(/\/$/, "");
		return pathname === '/' ? "home" : menuItems.find((item) => normalizePath(pathname) === item.path)?.key || "";
	}, [pathname]);
	
	return (
		<Menu
			mode="horizontal"
			className="border-none font-medium"
			disabledOverflow={true}
			selectedKeys={[selectedKey]}
			onClick={({ key }) => {
				const selectedItem = menuItems.find((item) => item.key === key);
				if (selectedItem) navigate(selectedItem.path);
				window.scrollTo({
					top: 0,
					behavior: "smooth",
				});
			}}>
			{menuItems.map(({ key, label }) => (
				<Menu.Item
					key={key}
					className="text-gray-600 hover:text-blue-600">
					{label}
				</Menu.Item>
			))}
		</Menu>
	);
};
