import { percentValueToUi } from "@/lib/admin-rate-percent";
import type { AgentParentCaps } from "@/types/api/admin-agent";

/** 是否为站点一级代理（根节点）。 */
export function isLineRootAgentNode(
  node: { is_root?: boolean; depth?: number } | null | undefined,
): boolean {
  return node != null && (node.is_root === true || node.depth === 0);
}

/** 一级代理占成/授信/回水仅超管可改；下级代理仍由上级维护。 */
export function isRootProfileEditableByActor(
  node: { is_root?: boolean; depth?: number } | null | undefined,
  isSuperAdmin: boolean,
): boolean {
  return isSuperAdmin || !isLineRootAgentNode(node);
}

/** 百分比字段硬顶（0–100）。 */
export const AGENT_PERCENT_HARD_MAX = 100;

/** 有上级时：回水上限不得超过上级回水上限与 100% 的较小值。 */
export function maxRebatePercentFromParent(parentCaps: AgentParentCaps | null): number {
  if (parentCaps === null) {
    return AGENT_PERCENT_HARD_MAX;
  }

  const parentLimit = Number(parentCaps.rebate_limit);
  if (!Number.isFinite(parentLimit) || parentLimit < 0) {
    return AGENT_PERCENT_HARD_MAX;
  }

  return Math.min(AGENT_PERCENT_HARD_MAX, parentLimit);
}

/** 默认玩家回水不得超过本节点回水上限与上级顶。 */
export function maxDefaultRebatePercent(
  rebateLimitText: string,
  parentCaps: AgentParentCaps | null,
): number {
  const rebateCap = maxRebatePercentFromParent(parentCaps);
  const ownLimit = Number.parseFloat(rebateLimitText);
  if (!Number.isFinite(ownLimit) || ownLimit < 0) {
    return rebateCap;
  }

  return Math.min(rebateCap, ownLimit);
}

/**
 * 授信额度上限：已有 baseline + 上级当前可下发（编辑下级时）。
 * 无上级（根代理）时不设顶，仅由业务校验 ≥ 已下发。
 */
export function maxCreditLimitFromParent(
  parentCaps: AgentParentCaps | null,
  baselineCreditLimit: number,
): number | undefined {
  if (parentCaps === null) {
    return undefined;
  }

  const baseline = Number.isFinite(baselineCreditLimit) ? Math.max(0, baselineCreditLimit) : 0;
  const parentAvailable = Number(parentCaps.available_credit);
  const extra = Number.isFinite(parentAvailable) ? Math.max(0, parentAvailable) : 0;

  return baseline + extra;
}

/** 实际占成 → 占上级比例（0–100）；无上级或上级占成为 0 时返回 null。 */
export function relativeSharePercentFromTotal(
  totalShareRate: number | null | undefined,
  parentTotalShareRate: number | null | undefined,
): number | null {
  const total = Number(totalShareRate);
  const parent = Number(parentTotalShareRate);
  if (!Number.isFinite(total) || !Number.isFinite(parent) || parent <= 0) {
    return null;
  }

  return (total / parent) * 100;
}

/** 实际占成 → 占上级比例 UI 字符串（如 "50"）。 */
export function relativeShareRateUiFromTotal(
  totalShareRate: number | null | undefined,
  parentTotalShareRate: number | null | undefined,
): string | null {
  const relative = relativeSharePercentFromTotal(totalShareRate, parentTotalShareRate);
  return relative === null ? null : percentValueToUi(relative);
}

/** 相对占成（占上级 %）换算后的实际占成，不得超过上级总占成。 */
export function actualShareRateFromRelative(
  relativePercent: number,
  parentCaps: AgentParentCaps | null,
): number | null {
  if (parentCaps === null) {
    return null;
  }

  const parentRate = Number(parentCaps.total_share_rate);
  if (!Number.isFinite(parentRate) || parentRate < 0) {
    return null;
  }

  const relative = Number.isFinite(relativePercent) ? relativePercent : 0;
  return Number(((parentRate * relative) / 100).toFixed(2));
}

export type AgentProfileValidationIssue =
  | { code: "share_range" }
  | { code: "share_exceeds_parent"; max: number }
  | { code: "credit_invalid" }
  | { code: "credit_exceeds_parent"; max: number }
  | { code: "credit_below_allocated"; min: number }
  | { code: "rebate_limit_range" }
  | { code: "default_rebate_range" }
  | { code: "default_exceeds_limit"; max: number }
  | { code: "rebate_exceeds_parent"; max: number };

export type AgentProfileScalarValidationInput = {
  shareRateText: string;
  creditLimitText: string;
  rebateLimitText: string;
  defaultRebateText: string;
  parentCaps: AgentParentCaps | null;
  baselineCreditLimit: number;
  minCreditLimit: number;
  usesRelativeShare: boolean;
  validateCredit: boolean;
};

function parsePercentField(value: string): number | null {
  const trimmed = value.trim();
  if (trimmed === "") {
    return null;
  }
  const parsed = Number.parseFloat(trimmed);
  return Number.isFinite(parsed) ? parsed : null;
}

/** 保存前校验占成/授信/回水是否在上级与已下发约束内。 */
export function validateAgentProfileScalars(
  input: AgentProfileScalarValidationInput,
): AgentProfileValidationIssue | null {
  const shareRate = Number.parseFloat(input.shareRateText);
  const creditLimit = Number.parseInt(input.creditLimitText, 10);
  const rebateLimit = parsePercentField(input.rebateLimitText);
  const defaultRebate = parsePercentField(input.defaultRebateText);

  if (Number.isNaN(shareRate) || shareRate < 0 || shareRate > AGENT_PERCENT_HARD_MAX) {
    return { code: "share_range" };
  }

  if (input.usesRelativeShare && input.parentCaps) {
    const actualShare = actualShareRateFromRelative(shareRate, input.parentCaps);
    const parentShare = Number(input.parentCaps.total_share_rate);
    if (
      actualShare !== null &&
      Number.isFinite(parentShare) &&
      actualShare > parentShare + 1e-9
    ) {
      return { code: "share_exceeds_parent", max: parentShare };
    }
  } else if (!input.usesRelativeShare && shareRate > AGENT_PERCENT_HARD_MAX) {
    return { code: "share_range" };
  }

  if (input.validateCredit) {
    if (Number.isNaN(creditLimit) || creditLimit < 0 || !Number.isInteger(creditLimit)) {
      return { code: "credit_invalid" };
    }

    const maxCredit = maxCreditLimitFromParent(input.parentCaps, input.baselineCreditLimit);
    if (maxCredit !== undefined && creditLimit > maxCredit) {
      return { code: "credit_exceeds_parent", max: maxCredit };
    }

    if (creditLimit < input.minCreditLimit) {
      return { code: "credit_below_allocated", min: input.minCreditLimit };
    }
  }

  if (rebateLimit === null || rebateLimit < 0 || rebateLimit > AGENT_PERCENT_HARD_MAX) {
    return { code: "rebate_limit_range" };
  }

  if (defaultRebate === null || defaultRebate < 0 || defaultRebate > AGENT_PERCENT_HARD_MAX) {
    return { code: "default_rebate_range" };
  }

  const parentRebateMax = maxRebatePercentFromParent(input.parentCaps);
  if (rebateLimit > parentRebateMax) {
    return { code: "rebate_exceeds_parent", max: parentRebateMax };
  }

  const defaultCap = maxDefaultRebatePercent(input.rebateLimitText, input.parentCaps);
  if (defaultRebate > defaultCap) {
    return { code: "default_exceeds_limit", max: defaultCap };
  }

  return null;
}

/** 授信额度相对 min/max 的越界类型（用于区分错误文案）。 */
export function creditLimitRangeIssue(
  value: string,
  options: { min: number; max?: number },
): "below_min" | "above_max" | null {
  const trimmed = value.trim();
  if (trimmed === "") {
    return null;
  }

  const parsed = Number.parseInt(trimmed, 10);
  if (!Number.isFinite(parsed)) {
    return null;
  }

  if (parsed < options.min) {
    return "below_min";
  }

  if (options.max !== undefined && parsed > options.max) {
    return "above_max";
  }

  return null;
}

export function isNumericStepperOutOfRange(
  value: string,
  options: { min?: number; max?: number; integer?: boolean },
): boolean {
  const trimmed = value.trim();
  if (trimmed === "") {
    return false;
  }

  const parsed = options.integer
    ? Number.parseInt(trimmed, 10)
    : Number.parseFloat(trimmed);
  if (!Number.isFinite(parsed)) {
    return true;
  }

  if (options.min !== undefined && parsed < options.min) {
    return true;
  }
  if (options.max !== undefined && parsed > options.max) {
    return true;
  }

  return false;
}
