"use client";

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

import { AdminSubnav, AdminSubnavLink } from "@/components/admin/admin-subnav";
import { Badge } from "@/components/ui/badge";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { PRD_RISK_ACCESS_ANY } from "@/lib/admin-prd";
import { canManageDrawResults, canViewDrawFinance, canViewDrawResults } from "@/lib/draw-access";
import { useDrawDetail } from "@/modules/draws/draw-detail-context";
import { useAdminProfile } from "@/stores/admin-session";

const segments = [
  { suffix: "", key: "status", label: "subnav.status", requiresManage: false },
  { suffix: "/results", key: "results", label: "subnav.results", requiresManage: false },
  { suffix: "/finance", key: "finance", label: "subnav.finance", requiresManage: false },
  { suffix: "/review", key: "review", label: "subnav.review", requiresManage: true },
  {
    suffix: "/risk/pools",
    key: "riskPools",
    label: "subnav.riskPools",
    requiresManage: false,
    requiresRisk: true,
  },
] as const;

function isRiskPoolsTabActive(pathname: string, base: string): boolean {
  const riskPrefix = `${base}/risk/`;
  if (!pathname.startsWith(riskPrefix)) {
    return false;
  }

  const rest = pathname.slice(riskPrefix.length);

  return (
    rest === "pools"
    || rest.startsWith("pools/")
    || rest === "hot"
    || rest === "sold-out"
  );
}

function isReviewTabActive(pathname: string, base: string): boolean {
  const reviewPrefix = `${base}/review`;
  const publishPrefix = `${base}/publish`;

  return (
    pathname === reviewPrefix
    || pathname.startsWith(`${reviewPrefix}/`)
    || pathname.startsWith(`${publishPrefix}/`)
  );
}

export function DrawSubnav({ drawId }: { drawId: string }): React.ReactElement {
  const { t } = useTranslation("draws");
  const pathname = usePathname();
  const base = `/admin/draws/${drawId}`;
  const profile = useAdminProfile();
  const perms = profile?.permissions ?? [];

  const canViewDraw = canViewDrawResults(perms);
  const canManageDraw = canManageDrawResults(perms);
  const canViewFinance = canViewDrawFinance(perms);
  const canViewRisk = adminHasAnyPermission(perms, [...PRD_RISK_ACCESS_ANY]);
  const { draw } = useDrawDetail();
  const pendingReview = draw?.result_batch_counts.pending_review ?? 0;

  const visibleSegments = useMemo(
    () =>
      segments.filter((segment) => {
        if (!canViewDraw) {
          return false;
        }
        if (segment.requiresManage && !canManageDraw) {
          return false;
        }
        if (segment.key === "finance" && !canViewFinance) {
          return false;
        }
        if ("requiresRisk" in segment && segment.requiresRisk && !canViewRisk) {
          return false;
        }

        return true;
      }),
    [canManageDraw, canViewDraw, canViewFinance, canViewRisk],
  );

  return (
    <AdminSubnav aria-label={t("subnav.aria", { defaultValue: "期号导航" })} className="mb-4">
      {visibleSegments.map(({ suffix, key, label }) => {
        const href = `${base}${suffix}`;
        const active =
          suffix === ""
            ? pathname === base || pathname === `${base}/`
            : suffix === "/review"
              ? isReviewTabActive(pathname, base)
              : key === "riskPools"
                ? isRiskPoolsTabActive(pathname, base)
                : pathname === href || pathname.startsWith(`${href}/`);

        return (
          <AdminSubnavLink key={key} href={href} active={active}>
            <span className="inline-flex items-center gap-1.5">
              {t(label)}
              {key === "review" && pendingReview > 0 ? (
                <Badge variant="secondary" className="h-5 min-w-5 px-1 text-[11px] tabular-nums">
                  {pendingReview}
                </Badge>
              ) : null}
            </span>
          </AdminSubnavLink>
        );
      })}
    </AdminSubnav>
  );
}
