"use client";

import Link from "next/link";
import { useTranslation } from "react-i18next";

import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { useAdminCurrencyCatalog, getCachedAdminCurrencies } from "@/hooks/use-admin-currency-catalog";
import { formatAdminMinorUnits } from "@/lib/money";
import { cn } from "@/lib/utils";
import { ReconcileItemActions } from "@/modules/reconcile/reconcile-item-actions";
import {
  itemCurrentStatusLabel,
  itemStatusLabel,
  mainSiteCheckLabel,
} from "@/modules/reconcile/reconcile-labels";
import { TableCell, TableRow } from "@/components/ui/table";
import type { AdminReconcileItemRow } from "@/types/api/admin-reconcile";

type ReconcileItemRowProps = {
  row: AdminReconcileItemRow;
  canWriteWallet: boolean;
  actionBusy: boolean;
  onCompleteCredit: (transferNo: string) => void;
  onReverse: (transferNo: string) => void;
  onManualProcess: (transferNo: string) => void;
};

function resolveDisplayCurrency(): string {
  const fallback = getCachedAdminCurrencies().find((row) => row.is_enabled && row.is_bettable)?.code;
  return fallback?.trim() || "NPR";
}

function isResolved(row: AdminReconcileItemRow): boolean {
  return row.is_resolved === true || row.resolved_at != null;
}

export function ReconcileItemRow({
  row,
  canWriteWallet,
  actionBusy,
  onCompleteCredit,
  onReverse,
  onManualProcess,
}: ReconcileItemRowProps): React.ReactElement {
  const { t } = useTranslation(["reconcile", "wallet"]);
  const formatTs = useAdminDateTimeFormatter();
  useAdminCurrencyCatalog();
  const currencyCode = resolveDisplayCurrency();
  const transferNo = row.side_a_ref ?? "";
  const resolved = isResolved(row);

  return (
    <TableRow className={cn(!resolved && "bg-amber-500/[0.04]")}>
      <TableCell className="min-w-[11rem] align-middle py-3">
        {transferNo ? (
          <Link
            href={`/admin/wallet/transfer-orders?transfer_no=${encodeURIComponent(transferNo)}`}
            className="font-mono text-sm font-medium hover:underline"
          >
            {transferNo}
          </Link>
        ) : (
          <span className="text-sm">—</span>
        )}
      </TableCell>
      <TableCell className="min-w-[10rem] align-middle py-3">
        {row.side_b_ref ? (
          <Link
            href={`/admin/wallet/transactions?txn_no=${encodeURIComponent(row.side_b_ref)}`}
            className="font-mono text-xs break-all hover:underline"
          >
            {row.side_b_ref}
          </Link>
        ) : (
          <span className="text-sm text-muted-foreground">—</span>
        )}
      </TableCell>
      <TableCell className="min-w-[7rem] align-middle py-3 text-sm">
        <span className="break-words">
          {mainSiteCheckLabel(row.main_site_check, t)}
        </span>
        {row.main_site_external_ref_no ? (
          <p className="mt-1 font-mono text-xs text-muted-foreground break-all">
            {row.main_site_external_ref_no}
          </p>
        ) : null}
      </TableCell>
      <TableCell className="min-w-[9rem] whitespace-nowrap align-middle py-3 font-mono text-xs">
        {formatTs(row.created_at)}
      </TableCell>
      <TableCell className="min-w-[7.5rem] align-middle py-3">
        <div className="space-y-1">
          <AdminStatusBadge
            status={row.status}
            className={cn(resolved && "border-border/60 bg-muted/40 text-muted-foreground")}
          >
            {itemStatusLabel(row.status, t)}
          </AdminStatusBadge>
          {resolved ? (
            <p className="text-[11px] leading-snug text-muted-foreground">{t("itemScanFindingResolvedHint")}</p>
          ) : null}
        </div>
      </TableCell>
      <TableCell className="min-w-[5.5rem] align-middle py-3">
        <AdminStatusBadge status={row.current_transfer_status ?? row.status}>
          {itemCurrentStatusLabel(row, t)}
        </AdminStatusBadge>
      </TableCell>
      <TableCell className="min-w-[5.5rem] align-middle py-3 text-right tabular-nums">
        <span
          className={cn(
            "text-sm font-semibold",
            row.difference_amount !== 0 ? "text-amber-700" : "text-muted-foreground",
          )}
        >
          {formatAdminMinorUnits(row.difference_amount, currencyCode)}
        </span>
      </TableCell>
      <TableCell className="w-[3.5rem] align-middle py-3">
        <div className="flex justify-center">
          <ReconcileItemActions
            row={row}
            canWriteWallet={canWriteWallet}
            busy={actionBusy}
            compact
            onCompleteCredit={onCompleteCredit}
            onReverse={onReverse}
            onManualProcess={onManualProcess}
          />
        </div>
      </TableCell>
    </TableRow>
  );
}