"use client";

import { useMemo } from "react";
import { useTranslation } from "react-i18next";

import { AdminNumericStepper } from "@/components/admin/admin-numeric-stepper";
import { Label } from "@/components/ui/label";
import { isNumericStepperOutOfRange } from "@/lib/agent-profile-caps";
import { formatCredit } from "@/modules/agents/agent-line-sidebar";

export type PlayerCreditLimitFieldProps = {
  id: string;
  value: string;
  onValueChange: (value: string) => void;
  parentAvailableCredit: number | null;
  /** 编辑已有玩家时传入当前授信，用于计算可上调上限 */
  baselineCreditLimit?: number;
};

export function PlayerCreditLimitField({
  id,
  value,
  onValueChange,
  parentAvailableCredit,
  baselineCreditLimit = 0,
}: PlayerCreditLimitFieldProps): React.ReactElement {
  const { t } = useTranslation(["agents"]);

  const maxCredit = useMemo(() => {
    if (parentAvailableCredit === null) {
      return undefined;
    }

    return baselineCreditLimit + parentAvailableCredit;
  }, [baselineCreditLimit, parentAvailableCredit]);

  return (
    <div className="space-y-2">
      <Label htmlFor={id} className="text-muted-foreground">
        {t("playersPanel.creditLimit", { defaultValue: "授信额度" })}
      </Label>
      <AdminNumericStepper
        id={id}
        value={value}
        onValueChange={onValueChange}
        min={0}
        max={maxCredit}
        step={1000}
        integer
      />
      {parentAvailableCredit !== null ? (
        <p className="text-[11px] text-muted-foreground/80">
          {t("playersPanel.availableToGrant", {
            defaultValue: "代理剩余可下发：{{amount}}",
            amount: formatCredit(parentAvailableCredit),
          })}
        </p>
      ) : null}
      {parentAvailableCredit !== null &&
      isNumericStepperOutOfRange(value, {
        min: 0,
        max: maxCredit,
        integer: true,
      }) ? (
        <p className="text-[11px] text-destructive">
          {t("playersPanel.creditLimitExceeded", {
            defaultValue: "授信额度不能超过当前代理可下发额度",
          })}
        </p>
      ) : null}
    </div>
  );
}
