"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import {
  getCreditLedger,
  type SettlementCreditLedgerRow,
} from "@/api/admin-agent-settlement";
import { AdminListPaginationFooter } from "@/components/admin/admin-list-pagination-footer";
import { AdminLoadingState } from "@/components/admin/admin-loading-state";
import { AdminTableLoadingRow } from "@/components/admin/admin-loading-state";
import { AdminTableNoResourceRow } from "@/components/admin/admin-no-resource-state";
import { AdminPlayerIdentityCells, AdminPlayerIdentityHeads } from "@/components/admin/admin-player-identity-columns";
import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { PlayerLedgerSourceBadge } from "@/components/admin/player-funding-badges";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
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";

const REASON_FILTERS = [
  "all",
  "game_settlement",
  "bet",
  "bill_settlement",
  "payment_record",
  "adjustment",
  "reversal",
  "bad_debt",
  "share_ledger",
] as const;

type ReasonFilter = (typeof REASON_FILTERS)[number];

const COL_SPAN = 11;

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 reasonLabel(
  value: ReasonFilter | string,
  t: ReturnType<typeof useTranslation<["settlementCenter", "wallet", "common"]>>["t"],
): string {
  if (value === "all") {
    return t("filters.statusAll", { defaultValue: "全部" });
  }
  return creditLedgerReasonLabel(value, t);
}

function CreditLedgerReasonBadge({ reason }: { reason: string }): React.ReactElement {
  const { t } = useTranslation(["settlementCenter"]);
  const label = creditLedgerReasonLabel(reason, t);
  
  let colorClass = "border-border bg-muted/30 text-foreground/80";
  
  if (reason.includes("payment") || reason.includes("settlement_payout")) {
    colorClass = "border-emerald-200/60 bg-emerald-50 text-emerald-700 dark:border-emerald-800/60 dark:bg-emerald-950/30 dark:text-emerald-400";
  } else if (reason.includes("game_settlement") || reason === "share_ledger") {
    colorClass = "border-blue-200/60 bg-blue-50 text-blue-700 dark:border-blue-800/60 dark:bg-blue-950/30 dark:text-blue-400";
  } else if (reason === "bet_hold" || reason === "bet_hold_release") {
    colorClass = "border-orange-200/60 bg-orange-50 text-orange-700 dark:border-orange-800/60 dark:bg-orange-950/30 dark:text-orange-400";
  } else if (reason === "adjustment" || reason === "reversal") {
    colorClass = "border-amber-200/60 bg-amber-50 text-amber-700 dark:border-amber-800/60 dark:bg-amber-950/30 dark:text-amber-400";
  } else if (reason === "bad_debt") {
    colorClass = "border-rose-200/60 bg-rose-50 text-rose-700 dark:border-rose-800/60 dark:bg-rose-950/30 dark:text-rose-400";
  }
  
  return (
    <span className={cn("inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium", colorClass)}>
      {label}
    </span>
  );
}

type SettlementCreditLedgerPanelProps = {
  adminSiteId: number;
  settlementPeriodId: number;
  currencyCode: string;
  refreshKey?: number;
};

export function SettlementCreditLedgerPanel({
  adminSiteId,
  settlementPeriodId,
  currencyCode,
  refreshKey = 0,
}: SettlementCreditLedgerPanelProps): React.ReactElement {
  const { t } = useTranslation(["settlementCenter", "wallet", "common"]);
  const formatTs = useAdminDateTimeFormatter();

  const [draftAccount, setDraftAccount] = useState("");
  const [draftReason, setDraftReason] = useState<ReasonFilter>("all");
  const [appliedAccount, setAppliedAccount] = useState("");
  const [appliedReason, setAppliedReason] = useState<ReasonFilter>("all");
  const [rows, setRows] = useState<SettlementCreditLedgerRow[]>([]);
  const [total, setTotal] = useState(0);
  const [truncated, setTruncated] = useState(false);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(20);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await getCreditLedger({
        admin_site_id: adminSiteId,
        settlement_period_id: settlementPeriodId,
        player_account: appliedAccount.trim() || undefined,
        reason: appliedReason === "all" ? undefined : appliedReason,
        page,
        per_page: perPage,
      });
      setRows(res.items ?? []);
      setTotal(res.total ?? 0);
      setTruncated(res.truncated === true);
    } finally {
      setLoading(false);
    }
  }, [adminSiteId, appliedAccount, appliedReason, page, perPage, settlementPeriodId]);

  useEffect(() => {
    void load();
  }, [load, refreshKey]);

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

  const refLabel = (row: SettlementCreditLedgerRow): string => {
    const parts: string[] = [];
    const ticketLabel = row.ticket_item_id ? `#${row.ticket_item_id}` : null;
    const billLabel = row.settlement_bill_id ? `#${row.settlement_bill_id}` : null;
    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 (ticketLabel) {
      parts.push(ticketLabel);
    }
    if (billLabel) {
      parts.push(billLabel);
    }

    const normalizedParts = parts
      .map((part) => {
        let normalized = part;
        if (billLabel) {
          normalized = normalized.replace(new RegExp(`\\bbill${billLabel.replace("#", "\\#")}\\b`, "g"), "");
        }
        if (ticketLabel) {
          normalized = normalized.replace(new RegExp(`\\bticket_item${ticketLabel.replace("#", "\\#")}\\b`, "g"), "");
        }

        return normalized
          .split(" · ")
          .map((segment) => segment.trim())
          .filter(Boolean)
          .join(" · ");
      })
      .filter(Boolean);

    const uniqueParts = normalizedParts.filter((part, index) => {
      if (normalizedParts.indexOf(part) !== index) {
        return false;
      }
      if (billLabel && part !== billLabel && part.endsWith(billLabel)) {
        return false;
      }
      if (ticketLabel && part !== ticketLabel && part.endsWith(ticketLabel)) {
        return false;
      }

      return true;
    });

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

  const statusLabel = (row: SettlementCreditLedgerRow): string => {
    if (row.bill_status) {
      return settlementBillStatusLabel(row.bill_status, t);
    }
    if (row.status === "posted") {
      return t("creditLedger.status.posted", { defaultValue: "已入账" });
    }

    return row.status || "—";
  };

  return (
    <div className="space-y-4">


      <div className="admin-list-toolbar">
        <div className="admin-list-field">
          <Label htmlFor="scl-player" className="sm:shrink-0">
            {t("creditLedger.columns.player", { defaultValue: "玩家" })}
          </Label>
          <Input
            id="scl-player"
            className="h-9"
            value={draftAccount}
            placeholder={t("ledgerPanel.playerAccountPh", { defaultValue: "用户名 / 站点玩家 ID" })}
            onChange={(e) => setDraftAccount(e.target.value)}
          />
        </div>

        <div className="admin-list-field">
          <Label htmlFor="scl-reason" className="sm:shrink-0">
            {t("creditLedger.columns.reason", { defaultValue: "业务类型" })}
          </Label>
          <Select
            modal={false}
            value={draftReason}
            onValueChange={(v) => setDraftReason((v ?? "all") as ReasonFilter)}
          >
            <SelectTrigger id="scl-reason" className="h-9 w-full sm:w-52">
              <SelectValue>{() => reasonLabel(draftReason, t)}</SelectValue>
            </SelectTrigger>
            <SelectContent>
              {REASON_FILTERS.map((value) => (
                <SelectItem key={value} value={value}>
                  {reasonLabel(value, t)}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="admin-list-actions">
          <Button
            type="button"
            size="sm"
            onClick={() => {
              setAppliedAccount(draftAccount);
              setAppliedReason(draftReason);
              setPage(1);
            }}
          >
            {t("ledgerPanel.searchBtn", { defaultValue: "搜索" })}
          </Button>
          <Button
            type="button"
            size="sm"
            variant="secondary"
            onClick={() => {
              setDraftAccount("");
              setDraftReason("all");
              setAppliedAccount("");
              setAppliedReason("all");
              setPage(1);
            }}
          >
            {t("ledgerPanel.reset", { defaultValue: "重置筛选" })}
          </Button>
          <Button type="button" size="sm" variant="secondary" disabled={loading} onClick={() => void load()}>
            {t("ledgerPanel.refresh", { defaultValue: "刷新当前页" })}
          </Button>
        </div>
      </div>

      {truncated ? (
        <p className="rounded-lg border border-amber-200/70 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">
          {t("ledgerPanel.truncated", {
            defaultValue: "流水条数较多，当前列表可能未包含全部记录。请缩小筛选范围或按玩家账号查询。",
          })}
        </p>
      ) : null}

      {loading && rows.length === 0 ? <AdminLoadingState /> : null}

      <div className="admin-table-shell overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="whitespace-nowrap">
                {t("creditLedger.columns.txn", { defaultValue: "流水号" })}
              </TableHead>
              <AdminPlayerIdentityHeads />
              <TableHead className="whitespace-nowrap">
                {t("columns.directAgent", { defaultValue: "直属代理" })}
              </TableHead>
              <TableHead className="whitespace-nowrap">
                {t("creditLedger.columns.channel", { defaultValue: "渠道" })}
              </TableHead>
              <TableHead className="whitespace-nowrap">
                {t("creditLedger.columns.reason", { defaultValue: "业务类型" })}
              </TableHead>
              <TableHead className="whitespace-nowrap">
                {t("columns.billId", { defaultValue: "账单 ID" })}
              </TableHead>
              <TableHead className="whitespace-nowrap">
                {t("columns.status", { defaultValue: "状态" })}
              </TableHead>
              <TableHead className="whitespace-nowrap text-right">
                {t("creditLedger.columns.amount", { defaultValue: "金额" })}
              </TableHead>
              <TableHead className="whitespace-nowrap">
                {t("creditLedger.columns.ref", { defaultValue: "关联" })}
              </TableHead>
              <TableHead className="whitespace-nowrap">
                {t("creditLedger.columns.time", { defaultValue: "时间" })}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading && rows.length === 0 ? (
              <AdminTableLoadingRow colSpan={COL_SPAN} />
            ) : rows.length === 0 ? (
              <AdminTableNoResourceRow
                colSpan={COL_SPAN}
                message={t("creditLedger.emptyPeriod", {
                  defaultValue: "本账期暂无流水审计记录。",
                })}
              />
            ) : (
              rows.map((row) => {
                const signed = signedLedgerAmount(row);
                return (
                  <TableRow key={row.row_key}>
                    <TableCell className="font-mono text-xs">{row.txn_no}</TableCell>
                    <AdminPlayerIdentityCells row={row} />
                    <TableCell className="text-xs">{row.direct_agent_label ?? "—"}</TableCell>
                    <TableCell>
                      <PlayerLedgerSourceBadge ledgerSource={row.ledger_source} />
                    </TableCell>
                    <TableCell>
                      <CreditLedgerReasonBadge reason={row.biz_type} />
                    </TableCell>
                    <TableCell className="tabular-nums text-xs">
                      {row.settlement_bill_id ? `#${row.settlement_bill_id}` : "—"}
                    </TableCell>
                    <TableCell>
                      <AdminStatusBadge
                        status={row.bill_status ?? row.status ?? "posted"}
                        tone={resolveCreditLedgerRowStatusTone(row)}
                      >
                        {statusLabel(row)}
                      </AdminStatusBadge>
                    </TableCell>
                    <TableCell className="tabular-nums text-right text-xs">
                      <span className={cn(signedLedgerAmountClass(signed))}>
                        {row.biz_type === "bet_hold"
                          ? t("creditLedger.reason.freezeAmount", {
                              defaultValue: "冻结 {{amount}}",
                              amount: formatAdminMinorUnits(row.amount, currencyCode),
                            })
                          : formatSignedLedgerAmount(signed, currencyCode)}
                      </span>
                    </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>
                      ) : row.settlement_bill_id ? (
                        <span>{refLabel(row)}</span>
                      ) : (
                        "—"
                      )}
                    </TableCell>
                    <TableCell className="whitespace-nowrap font-mono text-[11px] text-muted-foreground">
                      {formatTs(row.created_at)}
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>

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