"use client";

import { useMemo, type Ref } from "react";
import { useTranslation } from "react-i18next";

import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { formatPlayerInstant } from "@/lib/player-datetime";
import { formatMinorAsCurrency } from "@/lib/money";
import type { WalletLogItem, WalletLogsData } from "@/types/api/wallet-logs";

/** 与 §4.9 筛选一致；接口 `type` 查询参数 */
export const WALLET_FLOW_FILTERS: { value: string; labelKey: string }[] = [
  { value: "", labelKey: "wallet.flow.all" },
  { value: "transfer_in", labelKey: "wallet.flow.transfer_in" },
  { value: "transfer_out", labelKey: "wallet.flow.transfer_out" },
  { value: "bet", labelKey: "wallet.flow.bet" },
  { value: "prize", labelKey: "wallet.flow.prize" },
  { value: "refund", labelKey: "wallet.flow.refund" },
  { value: "reversal", labelKey: "wallet.flow.reversal" },
];

/** 信用盘：无主站划转；文案强调占用/释放信用 */
export const CREDIT_FLOW_FILTERS: { value: string; labelKey: string }[] = [
  { value: "", labelKey: "wallet.creditFlow.all" },
  { value: "bet", labelKey: "wallet.creditFlow.bet" },
  { value: "credit_release", labelKey: "wallet.creditFlow.credit_release" },
  { value: "bill_settlement", labelKey: "wallet.creditFlow.bill_settlement" },
];

const FLOW_LABEL_FALLBACKS: Record<string, string> = {
  "wallet.flow.all": "全部",
  "wallet.flow.transfer_in": "转入",
  "wallet.flow.transfer_out": "转出",
  "wallet.flow.bet": "下注",
  "wallet.flow.prize": "派奖",
  "wallet.flow.refund": "退款",
  "wallet.flow.reversal": "冲正",
  "wallet.creditFlow.all": "全部",
  "wallet.creditFlow.bet": "占用额度",
  "wallet.creditFlow.credit_release": "释额",
  "wallet.creditFlow.bill_settlement": "账期收付",
  "wallet.creditFlow.win_credit": "中奖释额",
  "wallet.creditFlow.refund": "账期确认释额",
  "wallet.creditFlow.reversal": "退本释额",
};

export function logTypeLabel(
  type: string,
  t?: (key: string, options?: { defaultValue?: string }) => string,
  creditMode = false,
): string {
  const prefix = creditMode ? "wallet.creditFlow." : "wallet.flow.";
  const key = `${prefix}${type}`;
  return t?.(key, { defaultValue: FLOW_LABEL_FALLBACKS[key] ?? type }) ?? type;
}

function txnStatusLabel(
  status: string,
  t: (key: string, options?: { defaultValue?: string }) => string,
): string {
  return t(`wallet.txnStatus.${status}`, { defaultValue: status });
}

type WalletLogsBlockProps = {
  logs: WalletLogsData | null;
  logsLoading: boolean;
  loadingMore?: boolean;
  hasMore?: boolean;
  onLoadMore?: () => void;
  loadMoreRef?: Ref<HTMLDivElement>;
  filter: string;
  onFilterChange: (value: string) => void;
  currency: string;
  /** 独立流水页可隐藏标题或改文案 */
  title?: string;
  /** 信用盘：专用筛选项与列表文案 */
  creditMode?: boolean;
};

/** 类型筛选 + 列表（钱包盘待对账见钱包页横幅） */
export function WalletLogsBlock({
  logs,
  logsLoading,
  loadingMore = false,
  hasMore = false,
  onLoadMore,
  loadMoreRef,
  filter,
  onFilterChange,
  currency,
  title,
  creditMode = false,
}: WalletLogsBlockProps) {
  const { t } = useTranslation("player");
  const resolvedTitle =
    title
    ?? (creditMode
      ? t("wallet.creditFlowsTitle", { defaultValue: "信用流水" })
      : t("wallet.flowsTitle", { defaultValue: "钱包流水" }));
  const filters = useMemo(() => {
    const source = creditMode ? CREDIT_FLOW_FILTERS : WALLET_FLOW_FILTERS;
    return source.map((f) => ({
      ...f,
      label: t(f.labelKey, { defaultValue: FLOW_LABEL_FALLBACKS[f.labelKey] ?? f.labelKey }),
    }));
  }, [creditMode, t]);

  return (
    <>
      <section className="space-y-3">
        <div className="flex flex-col gap-2">
          <div>
            <h2 className="text-sm font-black text-[#0b3f96]">{resolvedTitle}</h2>
          </div>
          <div className="flex flex-wrap gap-1.5">
            {filters.map((f) => (
              <Button
                key={f.value || "all"}
                type="button"
                size="sm"
                variant={filter === f.value ? "default" : "outline"}
                className={
                  filter === f.value
                    ? "h-8 rounded-full bg-[#07459f] px-3 text-xs font-bold text-white hover:bg-[#063b88]"
                    : "h-8 rounded-full border-[#dce7f7] bg-white px-3 text-xs font-bold text-[#32518d] hover:bg-[#f8fbff]"
                }
                onClick={() => onFilterChange(f.value)}
              >
                {f.label}
              </Button>
            ))}
          </div>
        </div>

        {logsLoading && !logs ? (
          <Skeleton className="h-40 w-full rounded-lg" />
        ) : null}

        {logs ? (
          <>
            <p className="text-xs text-muted-foreground">
              {t("wallet.totalRecords", { total: logs.total })}
            </p>
            <ul className="space-y-2">
              {logs.items.length === 0 ? (
                <li className="rounded-lg border border-dashed py-8 text-center text-sm text-muted-foreground">
                  {t(creditMode ? "wallet.emptyCreditLogs" : "wallet.emptyLogs", {
                    defaultValue: creditMode ? "暂无信用流水" : "暂无流水",
                  })}
                </li>
              ) : (
                logs.items.map((row) => (
                  <LogRow
                    key={row.log_id}
                    item={row}
                    currency={currency}
                    creditMode={creditMode}
                  />
                ))
              )}
            </ul>
            {logs.items.length > 0 ? (
              <>
                <div ref={loadMoreRef} className="min-h-1" />
                {hasMore ? (
                  <Button
                    type="button"
                    variant="outline"
                    className="h-10 w-full rounded-xl border-[#dce7f7] bg-white text-sm font-bold text-[#32518d] hover:bg-[#f8fbff]"
                    disabled={loadingMore}
                    onClick={onLoadMore}
                  >
                    {loadingMore
                      ? t("actions.loading")
                      : t("actions.loadMore")}
                  </Button>
                ) : (
                  <p className="py-2 text-center text-xs text-slate-400">
                    {t("wallet.noMoreLogs")}
                  </p>
                )}
              </>
            ) : null}
          </>
        ) : null}
      </section>
    </>
  );
}

export function LogRow({
  item,
  currency,
  creditMode = false,
}: {
  item: WalletLogItem;
  currency: string;
  creditMode?: boolean;
}) {
  const { t } = useTranslation("player");
  const ccy = item.currency_code || currency;
  const isIn = item.direction === "in";
  const statusTone = item.status === "posted"
    ? "border-emerald-200 bg-emerald-50 text-emerald-700"
    : item.status === "pending_reconcile"
      ? "border-amber-200 bg-amber-50 text-amber-700"
      : item.status === "reversed"
        ? "border-slate-200 bg-slate-50 text-slate-600"
        : "border-blue-200 bg-blue-50 text-blue-700";

  return (
    <li className="rounded-2xl border border-[#e1eaf6] bg-white px-3 py-3 text-sm shadow-[0_10px_28px_rgba(15,23,42,0.06)]">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <span className={isIn ? "size-2.5 rounded-full bg-emerald-500" : "size-2.5 rounded-full bg-[#e5002c]"} aria-hidden />
            <p className="truncate text-base font-black leading-tight text-[#101a33]">
              {logTypeLabel(item.type, t, creditMode)}
            </p>
          </div>
          <p className="mt-1.5 text-xs font-medium text-slate-500">
            {formatPlayerInstant(item.created_at)}
          </p>
          {item.ref_id ? (
            <p className="mt-1 truncate font-mono text-[11px] text-slate-400">
              {item.ref_id}
            </p>
          ) : null}
        </div>

        <div className="flex shrink-0 flex-col items-end gap-2 text-right">
          <p className={isIn ? "text-lg font-black tabular-nums text-emerald-600" : "text-lg font-black tabular-nums text-[#e5002c]"}>
            {isIn ? "+" : "−"}
            {formatMinorAsCurrency(item.amount_abs, ccy)}
          </p>
          <span className={`inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-black ${statusTone}`}>
            {txnStatusLabel(item.status, t)}
          </span>
        </div>
      </div>

      <div className="mt-3 flex items-center justify-between rounded-xl bg-[#f8fbff] px-3 py-2 text-xs">
        <span className="font-semibold text-slate-500">
          {creditMode ? t("wallet.creditAvailableAfter") : t("wallet.balanceAfter")}
        </span>
        <span className="font-mono font-black tabular-nums text-[#32518d]">
          {item.balance_after != null
            ? formatMinorAsCurrency(item.balance_after, ccy)
            : "—"}
        </span>
      </div>
    </li>
  );
}
