"use client";

import Link from "next/link";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useTranslationRef } from "@/hooks/use-translation-ref";

import {
  getCreditLedger,
  type SettlementCreditLedgerRow,
} from "@/api/admin-agent-settlement";
import { getAdminIntegrationSites } from "@/api/admin-integration-sites";
import { AdminListPaginationFooter } from "@/components/admin/admin-list-pagination-footer";
import { AdminTableLoadingRow } from "@/components/admin/admin-loading-state";
import { AdminTableNoResourceRow } from "@/components/admin/admin-no-resource-state";
import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { PlayerLedgerSourceBadge } from "@/components/admin/player-funding-badges";
import { AdminTableMoney } from "@/components/admin/admin-table-money";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { resolveAdminSiteId } from "@/lib/resolve-admin-site-id";
import { resolveCreditLedgerRowStatusTone } from "@/lib/admin-status-tone";
import { formatAdminMinorUnits } from "@/lib/money";
import { cn } from "@/lib/utils";
import {
  creditLedgerReasonLabel,
  settlementBillStatusLabel,
} from "@/modules/settlement/settlement-status-label";
import { useAdminProfile } from "@/stores/admin-session";
import { LotteryApiBizError } from "@/types/api/errors";

function signedLedgerAmount(row: SettlementCreditLedgerRow): number {
  if (typeof row.signed_amount === "number") {
    return row.signed_amount;
  }

  return row.direction === 1 ? row.amount : -row.amount;
}

function signedLedgerAmountClass(signed: number): string {
  if (signed < 0) {
    return "font-medium text-destructive";
  }
  if (signed > 0) {
    return "font-medium text-emerald-700 dark:text-emerald-400";
  }

  return "text-muted-foreground";
}

function formatSignedLedgerAmount(signed: number, currencyCode: string): string {
  if (signed === 0) {
    return formatAdminMinorUnits(0, currencyCode);
  }

  const prefix = signed < 0 ? "−" : "+";
  return `${prefix}${formatAdminMinorUnits(Math.abs(signed), currencyCode)}`;
}

function CreditLedgerReasonBadge({ reason }: { reason: string }): React.ReactElement {
  const { t } = useTranslation(["settlementCenter"]);
  const label = creditLedgerReasonLabel(reason, t);

  return (
    <span className="inline-flex items-center rounded-full border border-border bg-muted/30 px-2 py-0.5 text-xs font-medium text-foreground/80">
      {label}
    </span>
  );
}

function refLabel(row: SettlementCreditLedgerRow): string {
  const parts: string[] = [];
  if (row.biz_no) {
    parts.push(row.biz_no);
  }
  if (row.draw_no) {
    parts.push(row.draw_no);
  }
  if (row.play_code) {
    parts.push(row.play_code);
  }
  if (row.ticket_item_id) {
    parts.push(`#${row.ticket_item_id}`);
  }
  if (row.settlement_bill_id) {
    parts.push(`#${row.settlement_bill_id}`);
  }

  return parts.length > 0 ? parts.join(" · ") : "—";
}

type PlayerCreditLedgerTabProps = {
  playerId: number;
  siteCode: string;
  currencyCode: string;
};

export function PlayerCreditLedgerTab({
  playerId,
  siteCode,
  currencyCode,
}: PlayerCreditLedgerTabProps): React.ReactElement {
  const { t } = useTranslation(["players", "settlementCenter", "common"]);
  const tRef = useTranslationRef(["players", "common"]);
  const formatTs = useAdminDateTimeFormatter();
  const profile = useAdminProfile();

  const [adminSiteId, setAdminSiteId] = useState<number | null>(() =>
    resolveAdminSiteId(siteCode, profile),
  );
  const [siteResolveErr, setSiteResolveErr] = useState<string | null>(null);
  const [rows, setRows] = useState<SettlementCreditLedgerRow[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);
  const [loading, setLoading] = useState(true);
  const [loadErr, setLoadErr] = useState<string | null>(null);

  useAsyncEffect(() => {
    let cancelled = false;
    const fromProfile = resolveAdminSiteId(siteCode, profile);
    if (fromProfile !== null) {
      setAdminSiteId(fromProfile);
      setSiteResolveErr(null);
      return;
    }

    setSiteResolveErr(null);
    void getAdminIntegrationSites()
      .then((data) => {
        if (cancelled) {
          return;
        }
        const code = siteCode.trim().toUpperCase();
        const match = data.items.find((site) => site.code.trim().toUpperCase() === code);
        if (match) {
          setAdminSiteId(match.id);
        } else {
          setAdminSiteId(null);
          setSiteResolveErr(tRef.current("creditLedgerSiteNotFound", { defaultValue: "无法解析玩家所属站点" }));
        }
      })
      .catch(() => {
        if (!cancelled) {
          setAdminSiteId(null);
          setSiteResolveErr(tRef.current("loadFailed"));
        }
      });

    return () => {
      cancelled = true;
    };
  }, [profile, siteCode, tRef]);

  const load = useCallback(async () => {
    if (adminSiteId === null) {
      setRows([]);
      setTotal(0);
      setLoading(false);
      return;
    }

    setLoading(true);
    setLoadErr(null);
    try {
      const res = await getCreditLedger({
        admin_site_id: adminSiteId,
        player_id: playerId,
        page,
        per_page: perPage,
      });
      setRows(res.items ?? []);
      setTotal(res.total ?? 0);
    } catch (e) {
      setRows([]);
      setTotal(0);
      setLoadErr(e instanceof LotteryApiBizError ? e.message : tRef.current("loadFailed"));
    } finally {
      setLoading(false);
    }
  }, [adminSiteId, page, perPage, playerId, tRef]);

  useAsyncEffect(() => {
    if (adminSiteId === null) {
      setLoading(false);
      return;
    }
    void load();
  }, [adminSiteId, load]);

  const lastPage = Math.max(1, Math.ceil(total / Math.max(1, perPage)));
  const colSpan = 7;

  if (siteResolveErr) {
    return <p className="text-sm text-destructive">{siteResolveErr}</p>;
  }

  if (adminSiteId === null && !loading) {
    return (
      <p className="text-sm text-destructive">
        {t("creditLedgerSiteNotFound", { defaultValue: "无法解析玩家所属站点" })}
      </p>
    );
  }

  return (
    <div className="space-y-3">
      {loadErr ? (
        <div className="flex flex-wrap items-center gap-2">
          <p className="text-sm text-destructive">{loadErr}</p>
          <Button type="button" size="sm" variant="outline" onClick={() => void load()}>
            {t("retry", { ns: "common", defaultValue: "重试" })}
          </Button>
        </div>
      ) : null}

      <div className="admin-table-shell">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t("creditLedger.columns.txn", { ns: "settlementCenter", defaultValue: "流水号" })}</TableHead>
              <TableHead>{t("creditLedger.columns.channel", { ns: "settlementCenter", defaultValue: "渠道" })}</TableHead>
              <TableHead>{t("creditLedger.columns.reason", { ns: "settlementCenter", defaultValue: "业务类型" })}</TableHead>
              <TableHead className="text-center">{t("creditLedger.columns.amount", { ns: "settlementCenter", defaultValue: "金额" })}</TableHead>
              <TableHead>{t("creditLedger.columns.ref", { ns: "settlementCenter", defaultValue: "关联" })}</TableHead>
              <TableHead>{t("columns.status", { ns: "settlementCenter", defaultValue: "状态" })}</TableHead>
              <TableHead>{t("creditLedger.columns.time", { ns: "settlementCenter", defaultValue: "时间" })}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading && rows.length === 0 ? <AdminTableLoadingRow colSpan={colSpan} /> : null}
            {rows.map((row) => {
              const signed = signedLedgerAmount(row);
              const statusText = row.bill_status
                ? settlementBillStatusLabel(row.bill_status, t)
                : row.status === "posted"
                  ? t("creditLedger.status.posted", { ns: "settlementCenter", defaultValue: "已入账" })
                  : row.status || "—";

              return (
                <TableRow key={row.row_key}>
                  <TableCell className="font-mono text-xs">{row.txn_no}</TableCell>
                  <TableCell>
                    <PlayerLedgerSourceBadge ledgerSource={row.ledger_source} />
                  </TableCell>
                  <TableCell>
                    <CreditLedgerReasonBadge reason={row.biz_type} />
                  </TableCell>
                  <TableCell className={cn("text-center text-xs", signedLedgerAmountClass(signed))}>
                    <AdminTableMoney>
                      {row.biz_type === "bet_hold"
                        ? t("creditLedger.reason.freezeAmount", {
                            ns: "settlementCenter",
                            defaultValue: "冻结 {{amount}}",
                            amount: formatAdminMinorUnits(row.amount, currencyCode),
                          })
                        : formatSignedLedgerAmount(signed, currencyCode)}
                    </AdminTableMoney>
                  </TableCell>
                  <TableCell className="text-xs">
                    {row.ticket_item_id ? (
                      <Link
                        href={`/admin/tickets?ticket_item_id=${row.ticket_item_id}`}
                        className="text-primary underline-offset-2 hover:underline"
                      >
                        {refLabel(row)}
                      </Link>
                    ) : (
                      refLabel(row)
                    )}
                  </TableCell>
                  <TableCell>
                    <AdminStatusBadge
                      status={row.bill_status ?? row.status ?? "posted"}
                      tone={resolveCreditLedgerRowStatusTone(row)}
                    >
                      {statusText}
                    </AdminStatusBadge>
                  </TableCell>
                  <TableCell className="whitespace-nowrap font-mono text-xs text-muted-foreground">
                    {row.created_at ? formatTs(row.created_at) : "—"}
                  </TableCell>
                </TableRow>
              );
            })}
            {!loading && rows.length === 0 && !loadErr ? (
              <AdminTableNoResourceRow colSpan={colSpan} className="text-muted-foreground" />
            ) : null}
          </TableBody>
        </Table>
      </div>

      <AdminListPaginationFooter
        selectId="player-detail-credit-ledger"
        total={total}
        page={page}
        lastPage={lastPage}
        perPage={perPage}
        loading={loading}
        onPerPageChange={(n) => {
          setPerPage(n);
          setPage(1);
        }}
        onPageChange={setPage}
      />
    </div>
  );
}
