import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@/app/auth/AuthProvider.jsx";
import { getFrequentSecondLevelMenus } from "@/app/navigation/menuUsage.js";
import { formatMillis } from "@/shared/utils/time.js";

export function DashboardFrequentMenus({ menus = [] }) {
    const { user } = useAuth();
    const navigate = useNavigate();
    const frequentMenus = useMemo(() => getFrequentSecondLevelMenus({ menus, user }), [menus, user]);

    return (
        <section className="frequent-menu-section" aria-label="常用二级菜单">
            <div className="frequent-menu-head">
                <div>
                    <h2>常用页面</h2>
                    <p>本地缓存的二级菜单访问次数</p>
                </div>
            </div>
            {frequentMenus.length ? (
                <div className="frequent-menu-grid">
                    {frequentMenus.map((item) => {
                        const Icon = item.icon;
                        return (
                            <button
                                className="frequent-menu-card"
                                key={item.code}
                                type="button"
                                onClick={() => navigate(item.path)}
                            >
                                <span className="frequent-menu-card__icon">{Icon ? <Icon fontSize="small" /> : null}</span>
                                <span className="frequent-menu-card__group">{item.parentLabel}</span>
                                <strong>{item.label}</strong>
                                <span className="frequent-menu-card__meta">
                                    进入 {item.count || 0} 次 · {formatMillis(item.lastVisitedAtMs)}
                                </span>
                            </button>
                        );
                    })}
                </div>
            ) : (
                <div className="frequent-menu-empty">暂无本地访问记录</div>
            )}
        </section>
    );
}
