"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 { inferRebatePercentFromDimension, rateToPercentUi } from "@/modules/config/doc/odds-rebate-rates";
import { prizeScopeLabel, type PrizeScopeCode } from "@/modules/config/doc/prize-scopes";
import { cn } from "@/lib/utils";
import type { AdminPlayTypeRow, OddsItemRow, OddsVersionDetail } from "@/types/api/admin-config";

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

type SummaryRow = {
  label: string;
  value: string;
};

type OddsConfigSummaryPanelProps = {
  catTabLabel: string;
  playLabel: string;
  detail: OddsVersionDetail | null;
  draftRows: OddsItemRow[];
  types: AdminPlayTypeRow[];
  scopeRows: Partial<Record<PrizeScopeCode, OddsItemRow>>;
  playRebatePercent: string;
  className?: string;
};

export function OddsConfigSummaryPanel({
  catTabLabel,
  playLabel,
  detail,
  draftRows,
  types,
  scopeRows,
  playRebatePercent,
  className,
}: OddsConfigSummaryPanelProps) {
  const { t } = useTranslation("config");

  const isDraft = detail?.status === "draft";
  const isActive = detail?.status === "active";

  const rows: SummaryRow[] = [
    { label: t("odds.category"), value: catTabLabel },
    { label: t("odds.playType"), value: playLabel || "—" },
  ];

  for (const scope of ["first", "second", "third", "starter", "consolation"] as PrizeScopeCode[]) {
    const row = scopeRows[scope];
    rows.push({
      label: prizeScopeLabel(scope, t),
      value: row ? oddsMultiplierLabel(row.odds_value) : "—",
    });
  }

  rows.push({
    label: t("odds.rebateRate"),
    value: playRebatePercent,
  });

  rows.push(
    {
      label: t("rebate.fields.d2"),
      value: inferRebatePercentFromDimension(2, draftRows, types),
    },
    {
      label: t("rebate.fields.d3"),
      value: inferRebatePercentFromDimension(3, draftRows, types),
    },
    {
      label: t("rebate.fields.d4"),
      value: inferRebatePercentFromDimension(4, draftRows, types),
    },
  );

  const versionLabel = detail ? `v${detail.version_no}` : "—";

  return (
    <aside
      className={cn(
        "lg:sticky lg:top-24 lg:max-h-[calc(100vh-7rem)] lg: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">{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>

          <div className="flex flex-wrap items-center gap-2">
            <span className="text-sm text-muted-foreground">{t("odds.summary.statusLabel")}</span>
            {detail && !isDraft ? (
              <span className="inline-flex items-center rounded-md border border-border/60 bg-muted/40 px-2 py-0.5 text-xs font-medium text-muted-foreground">
                {t("odds.summary.readOnlyTag")}
              </span>
            ) : isDraft ? (
              <span className="inline-flex items-center rounded-md border border-primary/25 bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                {t("versionStatus.draft")}
              </span>
            ) : (
              <span className="text-sm">—</span>
            )}
          </div>

          <dl className="space-y-2.5">
            {rows.map((row) => (
              <div key={row.label} className="grid grid-cols-[minmax(0,1fr)_auto] gap-3 text-sm">
                <dt className="text-muted-foreground">{row.label}</dt>
                <dd className="font-mono text-right tabular-nums text-foreground">{row.value}</dd>
              </div>
            ))}
          </dl>

          {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>
          ) : 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>
  );
}

/** 当前玩法在摘要中展示的回水百分比（与赔率区输入一致）。 */
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));
}
