"use client";

import { FileText, Info } from "lucide-react";
import { useTranslation } from "react-i18next";

import { Alert, AlertDescription } from "@/components/ui/alert";
import { ConfigStatusBadge } from "@/modules/config/config-status-badge";
import { rateToPercentUi } from "@/modules/config/doc/odds-rebate-rates";
import { prizeScopeLabel, type PrizeScopeCode } from "@/modules/config/doc/prize-scopes";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { cn } from "@/lib/utils";
import type { ConfigVersionSummary, OddsItemRow, OddsVersionDetail } from "@/types/api/admin-config";

type OddsConfigSummaryPanelProps = {
  catTabLabel?: string;
  playLabel?: string;
  detail: OddsVersionDetail | null;
  scopeRows?: Partial<Record<PrizeScopeCode, OddsItemRow>>;
  playRebatePercent?: string;
  activeHead?: ConfigVersionSummary | null;
  /** 合并页：仅展示版本与操作提示，不重复主编辑区数值 */
  compact?: boolean;
  className?: string;
};

export function OddsConfigSummaryPanel({
  catTabLabel,
  playLabel,
  detail,
  scopeRows,
  playRebatePercent,
  activeHead = null,
  compact = false,
  className,
}: OddsConfigSummaryPanelProps) {
  const { t } = useTranslation("config");
  const formatDt = useAdminDateTimeFormatter();

  const isDraft = detail?.status === "draft";
  const isActive = detail?.status === "active";
  const versionLabel = detail ? `v${detail.version_no}` : "—";

  return (
    <aside
      className={cn(
        "xl:sticky xl:top-24 xl:max-h-[calc(100vh-7rem)] xl:overflow-y-auto",
        className,
      )}
    >
      <div className="overflow-hidden rounded-xl border border-border/60 bg-card">
        <div className="flex items-center gap-2 border-b border-border/50 px-4 py-3.5">
          <FileText className="size-4 text-primary" aria-hidden />
          <h3 className="text-base font-semibold">
            {compact ? t("odds.summary.contextTitle") : t("odds.summary.title")}
          </h3>
        </div>

        <div className="space-y-4 px-4 py-4">
          <div className="flex flex-wrap items-center gap-2">
            <span className="text-sm text-muted-foreground">{t("odds.summary.version")}</span>
            <span className="font-mono text-sm font-medium">{versionLabel}</span>
            {detail ? <ConfigStatusBadge status={detail.status} /> : null}
          </div>

          {activeHead ? (
            <div className="space-y-1 text-sm">
              <p className="text-muted-foreground">{t("odds.summary.activeVersion")}</p>
              <p className="font-mono font-medium">
                v{activeHead.version_no}
                {activeHead.effective_at ? ` · ${formatDt(activeHead.effective_at)}` : ""}
              </p>
            </div>
          ) : null}

          {!compact && catTabLabel && playLabel ? (
            <dl className="space-y-2 text-sm">
              <div className="grid grid-cols-[minmax(0,1fr)_auto] gap-3">
                <dt className="text-muted-foreground">{t("odds.category")}</dt>
                <dd>{catTabLabel}</dd>
              </div>
              <div className="grid grid-cols-[minmax(0,1fr)_auto] gap-3">
                <dt className="text-muted-foreground">{t("odds.playType")}</dt>
                <dd>{playLabel}</dd>
              </div>
            </dl>
          ) : null}

          {!compact && scopeRows ? (
            <dl className="space-y-2.5">
              {(["first", "second", "third", "starter", "consolation"] as PrizeScopeCode[]).map((scope) => {
                const row = scopeRows[scope];
                return (
                  <div key={scope} className="grid grid-cols-[minmax(0,1fr)_auto] gap-3 text-sm">
                    <dt className="text-muted-foreground">{prizeScopeLabel(scope, t)}</dt>
                    <dd className="text-right text-lg font-semibold text-foreground">
                      {row ? oddsMultiplierLabel(row.odds_value) : "—"}
                    </dd>
                  </div>
                );
              })}
              {playRebatePercent ? (
                <div className="grid grid-cols-[minmax(0,1fr)_auto] gap-3 text-sm">
                  <dt className="text-muted-foreground">{t("odds.rebateRate")}</dt>
                  <dd className="text-right text-lg font-semibold text-foreground">{playRebatePercent}</dd>
                </div>
              ) : null}
            </dl>
          ) : null}

          {detail && !isDraft ? (
            <Alert className="border-sky-500/30 bg-sky-500/5 text-foreground">
              <Info className="size-4 text-sky-600 dark:text-sky-400" aria-hidden />
              <AlertDescription className="text-xs leading-relaxed">
                {t("odds.summary.readOnlyHint")}
              </AlertDescription>
            </Alert>
          ) : isDraft ? (
            <Alert className="border-primary/25 bg-primary/5 text-foreground">
              <AlertDescription className="text-xs leading-relaxed">
                {t("odds.summary.draftHint")}
              </AlertDescription>
            </Alert>
          ) : isActive ? (
            <Alert className="border-emerald-500/30 bg-emerald-500/5 text-foreground">
              <AlertDescription className="text-xs leading-relaxed">
                {t("odds.summary.activeHint")}
              </AlertDescription>
            </Alert>
          ) : null}
        </div>
      </div>
    </aside>
  );
}

function oddsMultiplierLabel(oddsValue: number): string {
  return (oddsValue / 10000).toFixed(4);
}

/** 当前玩法在摘要中展示的回水百分比（与赔率区输入一致）。 */
export function playRebatePercentFromScopes(
  scopeRows: Partial<Record<PrizeScopeCode, OddsItemRow>>,
  order: readonly PrizeScopeCode[],
): string {
  const first = order.map((s) => scopeRows[s]).find(Boolean);
  if (!first) {
    return "0";
  }
  return rateToPercentUi(String(first.rebate_rate));
}
