"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";

import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { cn } from "@/lib/utils";
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: "subnavTransactions", requiredAny: RECONCILE_PERMS },
  { href: "/admin/wallet/transfer-orders", label: "subnavTransferOrders", requiredAny: RECONCILE_PERMS },
];

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

  return (
    <nav
      aria-label={t("subnavLabel")}
      className="flex w-full flex-wrap items-end gap-1 border-b border-border/60 px-1"
    >
      {tabs.map((tab) => {
        const allowed = adminHasAnyPermission(perms, [...tab.requiredAny]);
        const active = pathname === tab.href || pathname.startsWith(`${tab.href}/`);

        if (!allowed) {
          return (
            <span
              key={tab.href}
              className={cn(
                "border-b-2 border-transparent px-4 py-3 text-sm font-medium text-muted-foreground/45",
                "cursor-not-allowed",
              )}
              title={t("noPermission")}
            >
              {t(tab.label)}
            </span>
          );
        }

        return (
          <Link
            key={tab.href}
            href={tab.href}
            className={cn(
              "border-b-2 px-4 py-3 text-sm font-medium transition-colors",
              active
                ? "border-primary text-primary"
                : "border-transparent text-muted-foreground hover:border-border/80 hover:text-foreground",
            )}
          >
            {t(tab.label)}
          </Link>
        );
      })}
    </nav>
  );
}
