"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";

import { cn } from "@/lib/utils";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { useAdminProfile } from "@/stores/admin-session";

const RECONCILE_PERMS = [
  "prd.wallet_reconcile.manage",
  "prd.wallet_reconcile.view",
  "prd.wallet_reconcile.view_cs",
] as const;

const tabs: { href: string; label: string; requiredAny: readonly string[] }[] = [
  { href: "/admin/wallet/transactions", label: "钱包流水", requiredAny: RECONCILE_PERMS },
  { href: "/admin/wallet/transfer-orders", label: "转账单", requiredAny: RECONCILE_PERMS },
];

export function WalletSubnav(): React.ReactElement {
  const pathname = usePathname();
  const profile = useAdminProfile();
  const perms = profile?.permissions;

  return (
    <nav
      aria-label="钱包子页"
      className="mb-6 flex flex-wrap gap-2 border-b border-border pb-3"
    >
      {tabs.map((t) => {
        const allowed = adminHasAnyPermission(perms, [...t.requiredAny]);
        const active = pathname === t.href || pathname.startsWith(`${t.href}/`);
        const className = cn(
          "rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",
          active
            ? "bg-primary text-primary-foreground"
            : "bg-muted/60 text-foreground hover:bg-muted",
          !allowed && "cursor-not-allowed opacity-45",
        );
        if (!allowed) {
          return (
            <span key={t.href} className={className} title="当前账号无访问该页的权限">
              {t.label}
            </span>
          );
        }
        return (
          <Link key={t.href} href={t.href} className={className}>
            {t.label}
          </Link>
        );
      })}
    </nav>
  );
}
